I have a lot of select list (hundreds) like this (they have all the same name and id (I think my problem comes from here... but I can't change it):
<select name="custom_element_grid_class" id="custom_element_grid_class" class="select-size">
<option value="normal">normal</option>
<option value="square">square</option>
<option value="wide">wide</option>
<option value="tall">tall</option>
</select>
I want to get value of each list when an user change the value. I made this script but it only works on my fist select list...
jQuery("#custom_element_grid_class").change(function(){
var element = jQuery(this);
var selected = element.find('option:selected');
var size = selected.val();
var sclass = size + " element isotope-item";
jQuery(element).closest('.element').attr('class',sclass);
});
How can I make it works for all my select form?
EDIT: each select list comes from an ajx call, that's the reason I've got the same ID, but only in the futur DOM.
You cannot have double ID's.
So my suggestion in calling a function by inline onchange in the select.
For example:
<select name="custom_element_grid_class" id="custom_element_grid_class" onchange="func(this)" class="select-size">
And then your function:
function func(el){
var element = el;
var size = element.value;
var sclass = size + " element isotope-item";
jQuery(element).closest('.element').attr('class', sclass);
};
Demo here
I would suggest adding a first option with no value, so that, as you say "when an user change the value" you can read in case he took the first value.
If you can help it avoid duplicate IDs in exchange for classes. If this isn't an option use an attribute selector. Modifying the above code slightly.
Document Ready
$(function()
{
$('[name=custom_element_grid_class]').change(function(){
var $element = $(this);
var size = $element.val();
var sclass = size + " element isotope-item";
$element.closest('.element').attr('class',sclass);
});
});
Fiddle
Related
I want to know all the values of a select element once the change event is recorded on it.
Code is like this:
PHP
<select name='variant' class='variantsselect' onchange='on(this.value)'>
<option value='a'>a</option>
<option value='a'>a</option>
</select>
JAVASCRIPT
function on(value){
alert(value); //This gives me selected value
};
I need values a & b when change event is recorded on select element. Can someone help?
<select name='variant' class='variantsselect' onchange="javascript:valueselect(this)">
function valueselect(sel) {
var value = sel.options[sel.selectedIndex].value;
alert(value)
}
EDIT:
<select name='variant' id='variant' class='variantsselect' onchange="javascript:displayResult()">
function displayResult() {
var x = document.getElementById("variant");
var i;
var txt = "Text: ";
for (i = 0; i < x.length; i++) {
txt = txt + "\n" + x.options[i].text;
}
alert(txt);
}
You can store the last selected value in a variable and overwrite the variable with the new selected value at the end of your function. When the function is called the variable will = to the last option selected (If you don't set a default value the variable will be empty on the first call)
Click Here For Demo
OR
This will work for a simple hide/show select without having to remember the previous selection.
The hide/show content have a class name of HideShow, this class name css display is set to none. When you change the option it will loop through all elements using the class name HideShow to compare the selected value with the id of the element, if they match it will set the style display to block }else{ set style display to none.
Demo
function HideShow(Selection){
var HScontent=document.getElementsByClassName('HideShow');
for(var i=0; i<HScontent.length; i++){
if(HScontent[i].id==Selection){
HScontent[i].style.display="block";
}else{
HScontent[i].style.display="none";
}
}
}
.HideShow{display:none;}
<select onchange="HideShow(this.value);">
<option value="cars">Cars</option>
<option value="bikes">Bikes</option>
<option value="buses">Buses</option>
</select>
<div id="cars" class="HideShow">Cars content.....</div>
<div id="bikes" class="HideShow">Bikes content....</div>
<div id="buses" class="HideShow">Buses content....</div>
If you don't understand something in the demo, leave a comment below and I will try get back to you as soon as possible.
I hope this helps. Happy coding!
How can I put selected value of jquery multiselect dropdown into a hidden element's id? I need that id be an array so I can get the selected values of the multiselect into that.
What I tried is:
$( "#Myselect" ).change(function(){
var str = "";
$( "select option:selected" ).each(function() {
str += $( this ).val() + " ";
});
document.getElementById("objecttype").value = str;
}).trigger( "change" );
<html:hidden styleId="objecttype" property="objecttype" name="Myobjecttype"/>
but objecttype is just an id and isn't an array!
I assume you want this hidden field to be posted somewhere and used later on (server-side or whatever). Take a look at this Fiddle: http://jsfiddle.net/hm71689h/ it is roughly what you wanted.
Take into account what Haxxxton just said: you're joining the values using a delimiter (in this example a comma by default). You need to split that value into a new array later on.
Also, in your code-sample, you're referring to the hidden field using: document.getElementById("objecttype")
But you did not use an identifier, you used a name. Although you might think it should be the same, an ID is not the same as the name of an element.
I think you need smth like this:
HTML:
<select name="choice" multiple id="mySelect">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="hidden" name="myObjecttype" />
JS:
$('#mySelect').change(function(){
//brand new array each time
var foo = [];
//fills the array
foo = $("option:selected", this).map(function(){ return $(this).val() }).get();
//fills input with vals, as strings of course
$("input[name='myObjecttype']").val(foo);
//logs an array, if needed
console.log($("input[name='myObjecttype']").val().split(','));
});
Don't forget hidden input can't store array-/object- data, only strings. But you can easily make array.
See working jsfiddle: http://jsfiddle.net/sfvx5Loj/1/
I have an html select element, which includes three option elements. I have written a jquery code, which gives me the value of the title attribut from the current selected option element and saves that value in a variable (on the fly!).
But I would like to read a title attribute from an option value, which was not selected on the fly and which was already shown as selected value in my xhtml page, if the page was loaded as first.
This is my jQuery code and the second coderow doesn´t work correct:
$(document).ready(function(){
var optionElements = jQuery(jQuerySelektorHTMLSelectElement).children();
var OptionField = optionElements.find("[value=" + selectedValue + "]");
var OptionFieldTitleAttribut = OptionFeld.attr("title");
}
How can I find an option element, which was not selected on the fly but is selected, if the xhtml page was loaded?
If your variable jQuerySelektorHTMLSelectElement is well-named, you don't have to call children :
var selectElement = $(jQuerySelektorHTMLSelectElement); // <- remove children here
var OptionField = selectElement.find("[value=" + selectedValue + "]");
var OptionFieldTitleAttribut = OptionField.attr("title");
The find method already look for the selector in the children...
See this fiddle.
Try this:
html
<select id="test">
<option customAttr="a">test1</option>
<option customAttr="b">test2</option>
<option customAttr="c" selected="selected">test3</option>
<option customAttr="d">test4</option>
</select>
js
$(function(){
console.log($("#test").find("option:selected").attr("customAttr"));
});
fiddle
I have array of select dom and input textbox . On blur event of input(of perticular index) want to set the element in select dom value of same index.
My bind is working but after each blur event for different input box it is retiurning 0.
I am not able to set the select value i.e. (drop down)as per given index
JSFiddle
My code is following.
$(document).ready(function (){
var i =1;
$('#addme').on('click', function(){
var test = '<tr class="employee"><td><input type="text" id="emp_id['+i+']" /></td><td><select id="emp_name['+i+']" '
test += '<option value="-1" >Please Select </option><option value="e0001" >James Smith</option><option value="e0002" >Roger Sm</option>'
test +='<option value="e0003" >Elina Lobo</option></select></td></tr>'
$('#addme').after(test);
i++;
});
$(".employee input").live('blur',function(){
var inputIndex = $(this).index();
var inputValue = $(this).val();
alert("Input Index is :" + inputIndex + ' and value is ' + inputValue);
$('#emp_name[inputIndex]').each(function(){
if(this.value == inputValue){
$('#emp_name[inputIndex]').val($(this).val());
return false;
}
alert("Please iput valid value");
$('#emp_name[inputIndex]').val('-1');
});
});
});
</script>
<table />
<tr class="employee">
<td><input class="employee" type="text" id="emp_id[0]" /></td>
<td><select id="emp_name[0]" name="emp_name">
<option value="-1" >Please Select </option>
<option value="e0001" >James Smith</option>
<option value="e0002" >Roger Sm</option>
<option value="e0003" >Elina Lobo</option>
</select></td>
</tr>
<input type="button" id="addme" value="ADD ME"/>
</body>
</html>
You would need to delegate the events as you are adding the elements dynamically on the click of the button..
So $(".employee input").live('blur',function(){
should look something like this
$(staticContainer).on('blur',".employee input", function(){
staticContainer is the element that is already in the DOM when the elements are bound with the element.
Closer the container better the performance.
Also you have multiple issues with your code..
It is a better idea to append the rows to the table, so that the selector returns the right element inside the table.
$('#addme').after(test);
Supposed to be
$('table').append(test);
Next this selector does not replace the index value
$('#emp_name[inputIndex]')
supposed to be
$('#emp_name[' + inputIndex + ']')
Lastly the way you are accessing the indexes is completely wrong.
You are trying to get the current input with respective to the other elements . So
var inputIndex = $(this).index();
supposed to look like
var inputIndex = $('input').index(this); // which will give the right value.
Check Fiddle
First,jQuery .Index() means find the index of e's all siblings,not the index of the selector field,if you want to do so,you need a selector parameter.
So
var inputIndex = $(this).index();
should change to
var inputIndex = $(this).index(".employee input");
then your index part will work fine.
Second,I actually don't understand your blur event code part.You said you want to set the same index of select dom,why you compare the value?And you use the jQuery attribute selector and I didn't see any match element.I guess you try to select all select doms,and you try to alert on loop?I don't think it's a good idea.
I think you should rebuild this part,it has no logic and very hard to read now.
building on my last question jQuery getting values from multiple selects together
I have the select list like:
<select name="access" class="change" id="staff_off" runat="server">
<option value="8192">Off</option>
<option value="8192">On</option>
</select>
And I basically want to add or subtract the value of the options if it's off, subtract if it's on add it. It's going to be stored in a cookie (it uses bitwise)
The jquery I have is:
<script>
$(document).ready(function(){
var currentAccess = $.cookie("access");
})
$("select").change(function () {
var currentText = $(this).text()
var value = $(this).val()
$.cookie("access", value, { expires: 24 });
alert(currentText);
alert( $.cookie("access") );
})
</script>
I'll do the addition in the change function. The thing I can't work out is how to get the text of the select to do an if statement (so if it's yes, add the value, if it's no, subtract the value)
Tom
If you're looking for the inner text of the selected <option> element, you can use the :selected selector to match it, then call the text() method:
var currentText = $(this).find(":selected").text();
Or, alternatively:
var currentText = $(":selected", this).text();
To get the text of the selected item:
var value = $("#staff_off :selected").text();
I'd also suggest (if you're using HTML5) that using the data-x attribute to store the flag whether to add or subtract the value would be more semantic. Like this:
<select name="access" class="change" id="staff_off" runat="server">
<option value="8192" data-factor="-1">Off</option>
<option value="8192" data-factor="1">On</option>
</select>
Then to get your final value to apply to the total you simply multiply the value by the data-factor attribute.
You can use this $("#staff_off").find("option:selected").html();