Set option value with getElementsByName() - javascript

Having this fieldset:
<fieldset>
<legend>[*death]</legend>
<select name=death style="width: 120px">
<option value=Dead>[*died]
<option value=NotDead>[*alive]
<option value="" selected>-
</select>
</fieldset>
i want to set the [2].value to "-".
i have tried without any success:
document.getElementsByName('death')[2].checked = 'true';
document.getElementsByName('death')[2].value = '-';
Same kind of code works fine for radio boxes, checked boxes or other inputs in the form. How to do it with the option select (which is not an input)?
Thanks
[EDIT] of course, appropriate fieldset is:
<fieldset>
<legend>[*death]</legend>
<select name="death" style="width: 120px">
<option value="Dead">[*died]</option>
<option value="NotDead">[*alive]</option>
<option value="" selected>-</option>
</select>
</fieldset>
thanks.

It's a little bit unclear what you're asking. Are you simply asking to make the option at index 2 selected?
document.getElementsByName('death')[0].selectedIndex = 2;
Or, are you asking to change the value of option at index 2?
var d = document.getElementsByName('death')[0];
d.options[2].value = '-';

You need to manipulate the selected property of your select object, try
document.getElementsByName('death')[0].selectedIndex = 1;
In english, this reads "set the selected option to the second option in the first element in the document with name 'death'".
Fixing your HTML might make the results of your javascript more predictable. Close your tags, quote your attribute values, as follows:
<fieldset>
<legend>[*death]</legend>
<select name="death" style="width: 120px">
<option value="Dead">[*died]</option>
<option value="NotDead">[*alive]</option>
<option value="" selected>-</option>
</select>
</fieldset>

you can do this using jQuery... it's easy...
j("#death").val(2)

document.getElementsByName('death')[2] returns the third element named death - but you only have one element with that name. Instead, you want the first element named death (i.e. the one at index 0), and then you want its third option: document.getElementsByName('death')[0].options[2].value = ...

Here's an alert example of how to access your specific option values with getElementsByName
alert(document.getElementsByName('death')[0].options[0].value); // will return Dead
alert(document.getElementsByName('death')[0].options[1].value); // will return NotDead

Related

How do you properly "reset" a <select> element that supports multiple options in regular JS?

I want to be able to reset <select> tags by themselves instead of making them reset with the entire form. This is what I have so far:
<form autocomplete="off">
<select id="s" name="select" multiple>
<option disabled>Select a value!</option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
<button onclick="resetS()" type="button">Reset</button>
</form>
And the JS:
function resetS() {
const selectedOptions = document.getElementById('s').selectedOptions;
for (let i = 0; i < selectedOptions.length; i++) {
selectedOptions[i].selected = false;
}
}
When I first tried this, it seemed to work. However, only when one option is selected. I've noticed that when there is more than one option currently selected, it seems to break.
Starting with three options, and clicking the Reset button results in this, for some reason:
Every option gets deselected apart from one. Why does this happen?
Clicking the Reset button again deselects the one still selected option though.
You can set the selectedIndex attribute to -1 to indicate that no element is selected.
function resetS() {
const multipleSelect = document.getElementById('s');
multipleSelect.selectedIndex = -1;
}
<form autocomplete="off">
<select id="s" name="select" multiple>
<option disabled>Select a value!</option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
<button onclick="resetS()" type="button">Reset</button>
</form>
The list of selected <option> elements is a "live" list. When you change the selected flag on one of the elements, the list changes; that is, the <option> you changed disappears from the list, so the length gets 1 shorter. An indexed for loop will therefore skip elements.
The way to deal with that (well, one way) is to use a while loop as follows:
function resetS() {
const selectedOptions = document.getElementById('s').selectedOptions;
while (selectedOptions.length) {
selectedOptions[0].selected = false;
}
}
edit — or you could use the method suggested in Tom's answer, which is simpler.

Increment name tag for cloned elements

I have a form with cloned elements. The method of the form is POST. When I dump the result of the POST only the final 'select' box value is shown because they are all the same. How can I change the name tag to the cloned elements?
JSFiddle: https://jsfiddle.net/hLefegxz/
HTML
<div id="employees-div">
<label for="employees">Employee(s)</label>
<div class="select-wrapper" id="select-employees">
<select id="employees" name="employees" >
<option value="" selected disabled>- Select Employee -</option>
<option value="1"> Jason Bourne </option>
<option value="2"> James Bond </option>
<option value="3"> Ethan Hunt </option>
</select>
</div>
JS for the Clone
$(function() {
$("#addMore").click(function(e) {
var newSelect = $("#select-employees").clone();
newSelect.val("123");
$("#employees-div").append(newSelect);
});
});
At the moment all fo the elements have the same name tag of employees. It obviously needs to be different to go into the $_POST array. How can I go about making them different? I was thinking maybe of incrementing and keeping a count? It Currently is like so:
Don't worry about changing the name, you can and should use an array for the name, but you should worry about the id, since ids must be unique and you are cloning elements without changing the id of the new element.
By adding the [] to the input name it will be sent to the server as an array, for example, if you're using PHP you can get them from $_GET['employees'] which will be an array you can loop thru.
$(function() {
$("#addMore").click(function(e) {
var newSelect = $('select[name="employees[]"]:first').clone();
$("#select-employees").append("<br>");
$("#select-employees").append(newSelect);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="employees-div">
<label for="employees">Employee(s)</label>
<div class="select-wrapper" id="select-employees">
<select name="employees[]" >
<option value="" selected>- Select Employee -</option>
<option value="1"> Jason Bourne </option>
<option value="2"> James Bond </option>
<option value="3"> Ethan Hunt </option>
</select>
</div>
<button id=addMore>+ Employee</button>
Instead of using a name and increasing an integer on each "new employee", you could simply name your select to employees[]. That will send every employee in an array format to your server, allowing you to use an easy loop.
Your code as another problem though. ID should be unique, so every time you clone your select, you should change the ID.

Add/Removing Options with JQuery

I'd like to add and remove options from one drop down menu using JQuery given a selected option in another.
HTML:
<form action='quickLook.py' method = 'post'>
First DropDown Menu
Specify Channel:
<select id='bolometer'>
<option selected id='Dual' value = 'Dual' >Dual
<option id='Top' value = 'Top' >Top
<option id='Bottom' value = 'Bottom' >Bottom
</select>
Second DropDown Menu
<br>Specify Data to Display:
<select id='target'>
<option selected id='Spectrum' value = 'Spectrum'>Spectrum
<option id='Interferogram' value = 'Interferogram'>Interferogram
<option id='SNR' value = 'SNR'>SNR
<option id='Diff_Band' value = 'Diff_Band'> Diff_Band
</select>
<input type='submit' value= 'Query Images'>
</form>
I'd like to do something like this is JQuery:
$("#Dual").click(function() {
$("#target").append("#Diff_Band");
$("#target").remove("#Interferogram");
$("#target").remove("#SNR");
});
$("#Top").click(function() {
$("#target").append("#Interferogram");
$("#target").append("#SNR");
$("#Diff_Band").remove();
});
I want to append or remove the already written html.
What is the best way to do this?
Thank you for your time!
This is a similar problem I've encountered before working with Safari. A solution is to use .detach() instead of remove() as it keeps all jQuery data associated with the removed elements. Check this jsfiddle: http://jsfiddle.net/Ueu62/

How to use document.getElementsByTagName(

I want to use this function to work on all my drop down lists. Problem: the first drop down works okay, but hen I try select any option in the 2nd drop down selections. It places the value from the first group in the span of the second group. I want the span to have the value from its own group. I would like to use this on multiple groups.
The code below does not work properly. the phone number display okay but when i try to select the parts, the value of the phone number is displayed, no matter what the selection is.
I want the phone number when i select phones, and parts when i select parts.
Thank you
<script>function displayResult(xspan,xselect)
{
var x=document.getElementById(xselect).selectedIndex;
alert(x);
var newTxt = document.getElementsByTagName("option")[x].value;
document.getElementById(xspan).innerHTML = newTxt;
//alert(document.getElementsByTagName("option").length);
}
</script>
<select id="myPhones" onchange="displayResult('ShowPhone','myPhones')">
<option value="">Phone Numbers</option>
<optgroup label="Shipping">
<option value=" - 800-463-3339">FedEx</option>
<option value=""></option>
</optgroup>
</select>
<span id="ShowPhone"></span>
<select id="myParts" onchange="displayResult('ShowParts','myParts')">
<option value="">Qik Parts list</option>
<optgroup label="BATT">
<option value="1">1</option>
<option value="2">1</option>
<option value="2">1</option>
<option value="2"><1/option>
</optgroup>
</select>
<span id="ShowParts"></span>
Mostly comments:
When you do:
var newTxt = document.getElementsByTagName("option")[x].value;
then document.getElementsByTagName("option") returns all the options in the document, you probably only want the ones for the select in question. But the options for a select are available as a collection, so you can do:
selectElement.options[x].value;
But that is unnecessary unless you are dealing with very old browsers or IE where there are no value attributes. Just use selectElement.value.
Where you have:
<select id="myPhones" onchange="displayResult('ShowPhone','myPhones')">
you can instead do:
<select id="myPhones" onchange="displayResult('ShowPhone', this.value)">
so that you pass the current value of the select directly to the function. Then the function can be:
function displayResult(id, value) {
document.getElementById(id).innerHTML = value;
}
This should work, though I haven't tested it.
function displayResult(spanId, selectId) {
document.getElementById(spanId).innerHTML = document.getElementById(selectId).value;
}

html - how to get custom attribute of option tag in dropdown?

If I have this code:
<select onchange="alert('?');" name="myname" class="myclass">
<option isred="-1" value="hi">click</option>
</select>
How can I get the value '-1' from the custom attribute isred ?
I don't want to use the value property.
And I dont want to target the option tag by a name or id.
I want something like onchange="alert(this.getselectedoptionID.getAttribute('isred'));"
Can anyone help?
Also I don't want to use jquery.
You need to figure out what the selectedIndex is, then getAttribute from that options[] Array.
<select onchange="alert(this.options[this.selectedIndex].getAttribute('isred'));" name="myname" class="myclass">
<option isred="-1" value="hi">click</option>
<option isred="-5" value="hi">click</option>
</select>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
jsFiddle DEMO
As a side note:
Don't use inline javascript in your HTML. You want to separate your business logic from your UI. Create a javascript event handlers instead to handle this. (jQuery / Angular / etc)
in jquery, you can just write:
$("#myname").find(':selected').attr('isred');
Use something like this:
document.getElementById("x").onchange = function () {
console.log(this.options[this.selectedIndex].getAttribute("isred"));
};
//Pure Javascript solution, and elegant one check if you really want to leverage the power of javascript.
// Listening to a onchange event by ID attached with the select tag.
document.getElementById("name_your_id").onchange = function(event) {
//event.target.selectedOptions[0] have that option. as this is single selection by dropdown. this will always be 0th index :)
let get_val = event.target.selectedOptions[0].getAttribute("isred");
console.log("Value from the Attribute: ", get_val)
}
<select id="name_your_id" name="myname" class="myclass">
<option isred="423423" value="hi">One</option>
<option isred="-1" value="hi">Two</option>
</select>
Assuming we have a HTML markup as below:
<form id="frm_">
<select name="Veh">
<option value='-1' selected='selected'>Select</option>
<option value='0' ren='x'>xxx</option>
<option value='1' ren='y'>yyy</option>
</select>
</form>
The attr "ren" can be accessed like this:
function getRep() {
var ren = document.forms['frm_'].elements['Veh'].options[document.forms['frm_']
.elements['Veh'].selectedIndex].getAttribute('ren');
console.log("Val of ren " + ren); //x or y
}
Demo
You use: .getAttribute('isred')
You want:
<select onchange="alert(this.options[this.selectedIndex].getAttribute('isred'));" name="myname" class="myclass">
<option isred="-1" value="hi">click</option>
<option isred="-1" value="ho">click</option>
</select>
you can
$(".myclass").val(function(){alert($("option",this).attr("isred"));})

Categories