change select value in HTML5 template - html

I can change the value of a HTML select using JavaScript, but it fails when the select is in a HTML5 template.
For example, here is the HTML code:
<template id="sel_template">
<select id="sel">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</template>
<div id="put_here">
</div>
And the JavaScript code:
var t = document.querySelector("#sel_template");
var val = 2;
t.content.querySelector('#sel [value="' + val + '"]').selected = true;
var clone = document.importNode(t.content,true);
document.querySelector("#put_here").appendChild(clone);
The select value is "Cat" instead of "Fish".
jsfiddle: http://jsfiddle.net/dfroger/29kmerjh/1/
What's wrong?

You need to use setAttribute:
t.content.querySelector('#sel [value="' + val + '"]').setAttribute('selected', 'selected');
Fiddle

Related

How get html select > option tag custom attribute value using jquery?

I have research that in html you can add a custom attribute by simply adding data-* attribute inside html tag. I populate my select > option tag from my database:
<td>
<select onchange='setattr(this)' id='pitemnamerow"+ cnt +"' class='pitemname select2bs4 tselect'>
<option selected='selected'></option>
</select>
</td>
My Jquery and already set my custom tag
for (i in data.branditms) {
$('#pitemname'+brndid.id).append($('<option>', {
value: data.branditms[i]['item_id'],
text: data.branditms[i]['item_name'],
data-um: data.branditms[i]['um'], //custom-tag
}));
DOM result:
<select onchange="setattr(this)" id="pitemnamerow1" class="select2bs4 pitemname tselect select2-hidden-accessible" data-select2-id="pitemnamerow1" tabindex="-1" aria-hidden="true">
<option selected="selected" data-select2-id="81"></option>
<option value="0-RKM51" data-um="PC/s" data-select2-id="84">0-RING 2"DIAMETER</option>
<option value="UYD983" data-um="M" data-select2-id="84">Parts Wheel</option>
</select>
now when i try to access the custom attribute value it says undefine:
function setattr(brnditem){
var test = $(this).find('.pitemname').data('um');
console.log(test);
}
PS: My table row and select > options are also dynamic.
Any idea?
Try checking this:
var test = $(brnditem).find('option:selected').data('um');
also make sure the function was defined right before calling it on the 'select' tag
You should call data() instead attr(), rewrite you code like this :
function setattr(brnditem)
{
var test = $(brnditem).find("option:selected").data('um');
console.log(test);
}

i need a tampermonkey select a specify size command

Can I have the tampermonkey with jquery command for select a specify size? I have this situation:
<select name="group_1" id="group_1" class="attribute_select" onchange="findCombination();getProductAttribute();$('#wrapResetImages').show('slow');;">
<option title="44" value="19">44</option>
<option title="45" value="21">45</option>
<option title="46" value="23">46</option>
</select>
]
I used this command but it select size but doesn't work finally:
var size = "46";
var sliceright = size.length;
function setSelectedIndex (s, v) {
for ( var i = 0; i < s.options.length; i++ ) {
if ( s.options[i].text.slice(0,sliceright) == v ) {
s.options[i].selected = true;
return;
}
}
}
setSelectedIndex (document.getElementById('group_1'),size);
I'm not sure that I understand correctly your question, but If you want a JQuery selector to select a <option> by text instead of by value attribute you can try with:
var text = '46';
// select the element by id which has an <option> an contains
// the desired text. Then set the selected attribute
$('#group_1 option:contains("' + text + '")').attr('selected', 'selected');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="group_1" id="group_1" class="attribute_select">
<option title="44" value="19">44</option>
<option title="45" value="21">45</option>
<option title="46" value="23">46</option>
</select>
UPDATE:
After check out your example seems that in your web it's necessary to invoke click event after select an <option>. Also since all the <select> has a different id attribute but the same class, maybe it's more convenient use this as selector instead of the id. In short you can try with:
var text = '46';
$('.attribute_select option:contains("' + text + '")').attr('selected', 'selected').click();

change the value of a select tag using jquery

I am working on a wordpress site. I have an html with select tag and some options. When the form is submitted, I want to replace the value of option 'Other' with this value 'Rosemont' if option 'Other' is selected. Below is my html.
<select class="expand" name="field_19" id="field_19">
<option value="Bryn Mawr">Bryn Mawr</option>
<option value="Devon">Devon</option>
<option value="Gladwyne">Gladwyne</option>
<option value="Haverford">Haverford</option>
<option value="Other">Other</option>
</select>
Now I want that if the option 'Other' is selected then the selected value should be changed to text 'Rosemont'. So that the value 'Rosemont' should be saved into the database instead of 'Other'. I have written some jquery code but its not working.
Here is my code
jQuery(function(){
jQuery('#signup_submit').click(function(){
var city_name = jQuery('select[name="field_19"]').val();
alert(city_name)// this alerts 'Other'
if(city_name=='Other'){
valr = 'Rosemont';
jQuery('select[name="field_19"]').val(valr);
var vals = jQuery('select[name="field_19"]').val();
alert(vals);// again this alerts 'Other'. this should alert Rosemont
}
});
Something like this? jsBin demo
jQuery(function($) {
$('#signup_submit').click(function(e){
e.preventDefault();
var $f19 = $('select[name="field_19"]');
var f19Val = $f19.val();
if(f19Val=='Other'){
var $oth = $('[value=Other]',$f19);
var newVal = "Rosemont";
$oth.val(newVal).text(newVal);
}
});
});

Drop-down lists with the same content in HTML

Hello, community. Is it possible to specify a drop-down list structure at one place and to use it for several drop-down lists? For example, I need 5 drop-down lists all comprising 3 entries: "Basic", "Advanced", "Professional". Do I really need to write the following 5 times?
<select id="myid" name="myname" size="1">
<option value="1">Basic</option>
<option value="2">Advanced</option>
<option value="3">Professional</option>
</select>
BR
Ewgenij
I have done something similar recently.
It is simple. Look at my code below which I used to automatically enter dates for a select dropdown:
<select id="dateDropdown"></select> /*give an id for select*/
<script type="text/javascript">
var dateSelectId = document.getElementById("dateDropdown"); /*get the select element by its id*/
for (var i = 0; i < 8 ; i++) { /*for loop to create the options - in my case 8 options */
var currentDate = moment().subtract('d',i).format("MMM D"); /*ignore this - it basically just gives different dates for me*/
var paramObj = { /*declaring an obj for the 'option' tag's parameters*/
'optValue':i, /*value for the 'option' tag*/
'optText':currentDate /*text for 'option' tag*/
};
optionGenerator(dateSelectId,paramObj); /*function which actually creates <option> tags and assigns the parameters to it*/
};
Below is my javascript file which I import which contains the optionGenerator() function
/*Function to dynamically create select list and adding options to it*/
var optionGenerator = function(selectId,paramObj){
var optionInstance = document.createElement("option"); //creates child <option> element
optionInstance.value = paramObj.optValue;
optionInstance.text = paramObj.optText;
selectId.options.add(optionInstance); //adds the <option> tag with desired values
};
Let me know if you understood.
With php you can do like this
$select_box = "<select id='myid' name='myname' size='1'>
<option value='1'>Basic</option>
<option value='2'>Advanced</option>
<option value='3'>Professional</option>
</select>";
echo $select_box ;// where-ever you want in between your HTML tags
?>
eg,
<form >
<?php echo $select_box ; ?>
...other inputs...
</form>

getting the NAME of a select tag with javascript

I haven't found this question anywhere so I'm posting it here.
I have a bunch of select tags that are partially named using VBScript. I want to be able to get the name of a select tag that was called from the onchange event in javascript.
here is the code.
<select name="optWeeks_<%=intLineCnt%>" id = "name" onchange="changeWeek()">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<SCRIPT LANGUAGE = "JavaScript">
function changeWeek(){
var chosenoption = document.getElementsByTagName("select").name
}
</SCRIPT>
The select name - "optWeeks_<%=intLineCnt%>" is optWeeks prefixed with a number
I would like to know if I can get each name of the select tag that is called? Ex. optWeeks_1, optWeeks_2 etc.
Change the call to:
... onchange="changeWeek(this);">
Then you can simply;
function changeWeek(caller) {
var chosenoption = caller.name;
}
You need to get a reference to the element. this will be one in your event handler function. You can pass it to the function you are calling from there:
onchange="var element = this; changeWeek(element)">
I included the variable assignment above for clarity, you don't need it:
onchange="changeWeek(this)">
You can then get the name from the name property on that object:
function changeWeek(element) {
var name = element.name;
I'd generally recommend binding your event handlers with JS rather than HTML, not using HTML 3.2 though:
<select name="optWeeks_<%=intLineCnt%>" id="name">
<!-- … -->
</select>
<script>
var select = document.getElementById('name');
select.addEventListener('change', changeWeek);
function changeWeek(evt) {
var name = this.name;
}
</script>
Or you can use:
onchange="changeWeek(this.name)"
Or: (keep in mind that the changeWeek function will have to already have been defined)
<script>
var select = document.getElementById('name');
select.onchange = changeWeek;
</script>
addEventListener vs onclick -- for information between adding event listeners and the method I provided above.
An alternative JavaScript way:
var selects = document.getElementsByTagName('select');
for(var i in selects)
{
selects[i].onchange = function changeWeek(e) {console.log(e.target.name);}
}
HTML:
<select name="test">
<option>One</option>
<option>Two</option>
</select>
<select name="test2">
<option>One</option>
<option>Two</option>
</select>
Fiddle:
http://jsfiddle.net/bddwW/