Jump to content

Drop Down <select>


glenelkins

Recommended Posts

Hi

 

Just a quick one

 

Iv written some AJAX to change form values. How would i write in javascript something that would actually change the selected option of a <select> field. So it then displays the new one as selected

Link to comment
Share on other sites

you'll want to loop through the select box and set the element to selected where the value matches what it needs to:

 

http://www.webdeveloper.com/forum/archive/index.php/t-10247.html

 

you can also set the selected attribute of all the other elements (that don't match) to false.  if that doesn't actually adjust the select box on screen to be showing the one you've selected, you may need to blur and then focus on it?  not too sure.

Link to comment
Share on other sites

If you have something like this:

 

<select id='blah'>

<option name='1' value='one' selected="selected">One</option>

<option name='2' value='two'>Two</option>

<option name='3' value='three'>Three</option>

</select>

 

 

You can find the selected index with this code:

<script>
var e = document.getElementById("blah").selectedIndex;
</script>

 

The variable `e` will hold the index (which is a number) of the option selected. So if you want the value or text of that option, you can use this code:

<script>
var data = document.getElementById("blah").getElementsByTagName("option")[e];
var value = data.value;
var text = data.text;
</script>

 

Hope this helps.

Link to comment
Share on other sites

iv also been thinking of using ajax to regenerate the options and replace with js like this:

 

<select name="kjh">

    <div id="options"></div>

</select>

 

document.getElementById ( "options" ).innerHTML = "<option value='0'>bla</option>";

 

and setting the correct one as selected...but thats all long!

 

i wanted something quick to say ok this option is the one set in the database, set it to selected so it shows instantly on the screen regardless of what option was actually clicked on

 

make sense?

Link to comment
Share on other sites

iv also been thinking of using ajax to regenerate the options and replace with js like this:

 

<select name="kjh">

    <div id="options"></div>

</select>

 

document.getElementById ( "options" ).innerHTML = "<option value='0'>bla</option>";

 

and setting the correct one as selected...but thats all long!

 

i wanted something quick to say ok this option is the one set in the database, set it to selected so it shows instantly on the screen regardless of what option was actually clicked on

 

make sense?

Not fully. But with PHP, you can make the HTML and then put whatever option you want selected. Then use AJAX to do the rest.

Link to comment
Share on other sites

It sounds as if you are wanting to display the select list with an option pre-selected based upon what waws saved int he database. You shouldn't be using AJAX for this. As Ken2k7 alluded to you should be using PHP for this.

 

Example:

//Create the options for the select list
$colorOptions = array('Blue', 'Red', 'Green', 'Yellow');

//Query db for the saved value
$query = "SELECT favorite_color FROM users WHERE user_id = $userID";
$result = mysql_query($query) or die(mysql_error()."<br>Query: $query");

//Extract saved value
if (mysql_num_rows($result)) {
  $userData = mysql_fetch_assoc($result);
}

//Create select list and "select" the saved value
echo "<select name=\"favoriteColor\">";
foreach($colorOptions as $color) {
    $selected = ($color == $userData['favorite_color']) ? ' selected="selected"' : '' ;
    echo "<option value=\"$color\"$selected>$color</option";
}
echo "</select>";

Link to comment
Share on other sites

hi

 

ok yeh i do need it selecting from the database but not as the php executes or i would not be asking this question. the page has already been disaplayed, the dropdown has its values from the database. the user clicks a button, then a javascript function is run, ajax to get details from mysql then repopulates the form on the page without refresh. the point is im trying to re-select the correc option in the drop down at the same time

 

is this any clearer?

Link to comment
Share on other sites

hi

 

ok yeh i do need it selecting from the database but not as the php executes or i would not be asking this question. the page has already been disaplayed, the dropdown has its values from the database. the user clicks a button, then a javascript function is run, ajax to get details from mysql then repopulates the form on the page without refresh. the point is im trying to re-select the correc option in the drop down at the same time

 

is this any clearer?

No it's not. If you're using AJAX, why would the user's selected option change?

Link to comment
Share on other sites

Here's a quick sample script showing one way this can be done. When you click the button it repopulates the list with a new set of random options from a list. So, there is a possibility that the value you have already selected will be in the new list. If it is, that value will be selected. If not, the list defaults to the first item in the list.

<html>
<head>

<script type="text/javascript">

function changeSelect(selectField, newList, selectedVal) {

  selectField.options.length = 0;

  for (i=0; i<newList.length; i++) {
    selected = (selectedVal==newList[i]) ? true : false ;
    selectField.options[selectField.length] = new Option(newList[i], newList[i], selected, selected);
  }

}

function randArray(){
  return (Math.round(Math.random())-0.5);
} 

function changeColors() {

    //Array of all possible options
    colorArray = new Array('Blue','Green','Yellow','Orange','Red','Purple');
    //Randomize Array
    colorArray.sort( randArray );
    //Select first 5 options
    newOptions = colorArray.slice(0,4);

    selObj = document.getElementById('color');
    currentSelected = selObj.options[selObj.selectedIndex].value;

    changeSelect(selObj, newOptions, currentSelected);
}

</script>

</head>

<body onload="changeColors();">
<form name="test" method="POST" action="processingpage.php">

Color: 
<select name="country" id="color">
  <option></option>
</select>
<br>

<button onclick="changeColors();">Change Colors In List</button>

</form>
</body>
</html>

 

 

 

Link to comment
Share on other sites

akitchin's first answer is the closest idea i think may possibly work. but can you loop through the <option> tags without them being named as arrays like id="name[]"

 

the options aren't actually named as arrays.  the reason they are in the forum post i sent you is because it's actually using the array index to specify the option.  the element itself is the <select> box, while each individual option is an array element of that one (thus the array naming).  for example, say we have:

 

<select id="this_select">
<option>one</option>
<option>two</option>
<option>three</option>
</select>

 

i could use document.getElementById("this_select").options[0] to reference the "one" option.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.