Jump to content

Experiencing some strange problems while trying to append html code with javascipt

- - - - -

  • Please log in to reply
4 replies to this topic

#1
thatsme

thatsme

    Programmer

  • Members
  • PipPipPipPip
  • 176 posts
Hi. this code should take values from array categories, put them into dropdownlist and append that list to html's div (searchForm). However this code always appends new html tags like this : <div class='advancedSearchButton'>Search by category: <select name='category'></select></div><option>... all options goes here. Why does this happen?. I always iterate array first and only then add </select></div> to searchForm element. Moreover, when i commented addition of</select></div>, code still adds those tags before options. I would be grateful if someone could explain me what sort of x-files are happening here. searchForm and categories are initialized well

searchForm.innerHTML += "<div class='advancedSearchButton'>Search by category: <select name='category'>";
    var options = "";
    for (var i = 0; i < categories.length; i++){
        if (i == 0)
            options = "<option value='" + categories[i] + "' selected>" + categories[i] + "</option>";
        else
            options += "<option value='" + categories[i] + "'>" + categories[i] + "</option>";
    }
    searchForm.innerHTML += options; // + "</select></div>";


#2
Vaielab

Vaielab

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 547 posts
it's because your browser is a nice guy.
When he see that you open an <select> but forget to close it, he's kind enough to close it for you.

Insted of inserting directly into the DOM, insert everything (div, select and options) into a var and at the very end, insert it in searchForm

#3
thatsme

thatsme

    Programmer

  • Members
  • PipPipPipPip
  • 176 posts
thanks. It's a pitty that my browser is not nice enough to create entore website for me

#4
DarkLordofthePenguins

DarkLordofthePenguins

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 409 posts
If you want to create a dropdown list, a better method would be to have a list already in the HTML code and set its display: property in the CSS to "none", then when the user clicks the appropriate button, have Javascript change display to "block". This way user data is not lost. Like so:


<style type="text/css">

.dropdown{

	display: none;

}

</style>


...


<script type="text/javascript">

function show(){

	document.getElementById( "dropdown" ).style.display = "block".

}

</script>


As for diagnosing the problem with the innerHTML, I don't have enough information to help you with that. Your code looks fine from what I can tell. It may be something else that's the problem.
Programming is a journey, not a destination.

#5
thatsme

thatsme

    Programmer

  • Members
  • PipPipPipPip
  • 176 posts
thanks for a tip




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users