How I can add options to a select field based on the value of a text input?
This is my input text:
<input type="text" id="amount" size="30" />
This is my element I want to add to:
<span id="span_combo">
<select name="foo" id="combo">
<option value="1">1</option>
<option value="2">2</option>
</select>
</span>
This is my current JS:
$("#amount").keyup(function(){
var flag;
$("#combo").show("slow");
var a = $("#amount").val();
if(a==""){
$("#span_combo select").remove(true);
}
var i;
for(i=1;i<=a-1;i++){
$("#span_combo").append($("#span_combo select").first().clone(true));
}
});
Something like this should do it
Live demo here : http://jsfiddle.net/NdpuM/1/
$("#amount").keyup(function(){
var $combo = $('#combo');
$combo.html('');
var value = parseInt($('#amount').val(), 10);
for (i = 1; i <= value; i++) {
var $option = $('<option>').val(i).html(i);
$combo.append($option);
}
});
Basically, clear the select box everytime there is a keydown and repopulate it. You could optimize this more by adding a few checks to see whether it's the same value
If you want to rebuild the entire array:
$("#amount").keyup(function(){
$("#combo").show("slow");
var a = $("#amount").val();
if(a==""){
$("#span_combo select").remove(true);
}
$('#combo').empty();
for(var i=1;i<=a-1;i++){
$('<option />').attr('value', i)
.text(i)
.appendTo($('#combo'));
}
});
I think this could work:
$("#amount").keyup(function() {
var current = $("#combo option").length;
if(current < $(this).val()) {
for(var i = current + 1;i<=$(this).val();i++) {
$("#combo").append('<option value="'+i+'">'+i+'</option>');
}
} else {
for(var i=(parseInt($(this).val(),10)+1);i<=current;i++) {
$('#combo option[value="'+i+'"]').remove();
}
}
});
You might want to add input verification to this function, but it does what you want if you use it right.
EDIT: Just to clarify, this code doesn't clear the whole select box on every keyup event, it just adds new options or removes the last ones to get the specified amount of values.
Related
I noticed the jquery options and examples only accounted for the text and value attributes and when I tried to simply add the label attribute I got errors.
I would like the sort to also include the label attribute where the select box does not have a specific id but a unique name (autogenerated).
An example with Javascript or Jquery would be fine for this (using the list below)
<select multiple="true" style="width: 100px" size="6" name="staff_user_id_name[]">
<option label="dave matthews" value="1e7cfe4c-efc5-30fe-5135102574ac">dave matthews</option>
<option label="john adams" value="51803382-0a1e-44ec-511d461fd449">john adams</option>
<option label="justin timbers" value="471295fd-c3ae-9700-51487e79c590">justin timbers</option>
<option label="adam lion" value="a4dc7d17-36d0-8077-4f881e418250">adam lion</option>
<option label="june berstein" value="330bbd97-c025-e2e6-51fc14473736">june berstein</option>
</select>
jQuery(document).ready(function(){
// get the selected object by the beginning part of the name
var $sls = $('select[name^=staff_user_id_name]');
if ($sls.length > 0) {
var selectedVal = $sls.val();
var $options = $('option', $sls);
var arrVals = [];
$options.each(function () {
// push each option value and text into the array
arrVals.push({
val: $(this).val(),
text: $(this).text(),
});
});
arrVals.sort(function (a, b) {
if (a.text.toLowerCase() > b.text.toLowerCase()) {
{
return 1;
}
else if (a.text == b.text) {
return 0;
}
else {
return - 1;
}
});
// loop through the sorted array and set the text/values to the options
for (var i = 0, l = arrVals.length; i < l; i++) {
$($options[i]).val(arrVals[i].val).text(arrVals[i].text);
}
// set the selected value back
$sls.val(selectedVal);
}
} ); // end jQuery
You can do this by sorting the array of elements themselves and replacing the inner html with the newly sorted options
$('select[name^="staff_user_id_name"]').html(function(){
return $(this).children().sort(function(a,b){
return $(a).text().toLowerCase() > $(b).text().toLowerCase();
});
});
DEMO
My current jQuery selects the value attribute. How do I change my jQuery to select the data attribute "data-price"?
$('#trapfabric, #trapsize').on('change', function() {
var $selected = $('#trapfabric, #trapsize').children(":selected");
sum = parseInt($('#trapsize').val()) + parseInt($('#trapfabric').val());
$('#priceToSwap3').html('$' + sum
);
});
I know I have to fit something like this in the above but I can't get it to work:
$('#priceToSwap3').text($selected.data("price"))
EDITED
My HTML:
<span id="priceToSwap3"">$238</span>
<select id="trapsize" onChange="swapImage()">
<option data-price="238">foo</option>
<option data-price="288">foo</option>
</select>
<select id="trapfabric" onChange="swapImage()">
<option data-price="0">foo</option>
<option data-price="20">foo</option>
</select>
I believe this is what you want:
var $elements = $('#trapfabric, #trapsize');
$elements.on('change', function() {
var $selected = $elements.children(":selected");
var sum = 0;
$selected.each(function() {
sum += $(this).data('price');
});
$('#priceToSwap3').html('$' + sum);
});
You have to iterate over the selected elements to get the price datum of each of them.
DEMO
You are binding event to two elements #trapsize, #trapfabric if you want to get the source element you need to use $(this);
jsfiddle
$('#trapfabric, #trapsize').on('change', function() {
$('#priceToSwap3').text( '$' + $(':selected', this).data("price") );
});
We had a similar scenario wherein we assign security value(1,2,3 as security level) for each input. We have to change the security values "0" when the user logs into the system.
Eg:
<input type="text" security="3" id="super-admin" />
<input type="text" security="2" id="main-admin" />
<input type="text" security="1" id="normal-user" />
<script>
function userValidation(userType){
if(userType="super-admin"){
$("[security=1]").attr("security", 0);
$("[security=2]").attr("security", 0);
$("[security=3]").attr("security", 0);
}
if(userType="main-admin"){
$("[security=1]").attr("security", 0);
$("[security=2]").attr("security", 0);
}
if(userType="normal-user"){
$("[security=1]").attr("security", 0);
}
}
<script>
I'm integrating Postcode anywhere with my web project. I'm using a drop drop for the county/state field. Postcode anywhere returns the name of the County. Can I change the Selected Index when I only have the name? (I'm using a number for the value field which relates to a database field).
I tried the following:
var f = document.getElementById("state_dropdown");
f.options.[f.selectedIndex].text = response[0].County;
I've tried to include the drop down code html here but I can't get it to work properly for some reason.
But of course this just changes the text field for the item in the drop down that is already selected.
I can query the database and find out what ID I have assigned the county but I'd rather not if there is another way.
Loop over the options until you have a match:
for (var i = 0; i < f.options.length; i++) {
if (f.options[i].text == response[0].Country) {
f.options.selectedIndex = i;
break;
}
}
Demo.
I would make a function and loop over the labels:
See: http://jsfiddle.net/Y3kYH/
<select id="country" name="countryselect" size="1">
<option value="1230">A</option>
<option value="1010">B</option>
<option value="1213">C</option>
<option value="1013">D</option>
</select>
JavaScript
function selectElementByName(id, name) {
f = document.getElementById(id);
for(i=0;i<f.options.length;i++){
if(f.options[i].label == name){
f.options.selectedIndex = i;
break;
}
}
}
selectElementByName("country","B");
Just a variation on other answers:
<script type="text/javascript">
function setValue(el, value) {
var sel = el.form.sel0;
var i = sel.options.length;
while (i--) {
sel.options[i].selected = sel.options[i].text == value;
}
}
</script>
<form>
<select name="sel0">
<option value="0" selected>China
<option value="1">Russia
</select>
<button type="button" onclick="setValue(this, 'Russia');">Set to Russia</button>
<input type="reset">
</form>
I would like to know how can we arrange the three select box, with having some options, it will be configured according to the previous select box value.
Please look at the code which we applied for our program.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var rtype = $("#rtype").val();
var rarray = rtype.split(' ');
var max_adults = rarray[1];
var min_adults = rarray[0];
//var max_adults = 3;
//var min_adults = 2;
$('#rooms').change(function(){
var room_num = $(this).val();
var options = '';
for (var i = min_adults * room_num; i <= max_adults * room_num; i++) { options += '<option value="'+i+'">'+i+'</option>' } $('#person').html(options); }); $('#rooms').change(); });
</script>
</head>
<body>Room Type <select name="rtype" id="rtype"><option Selected value="">Select</option><option value="2 3">Room 2-3</option> <option value="3 4">Room 3-4</option></select> Category: <select name="rooms" id="rooms"> <option Selected value="">Select</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option> </select>Persons<select name="person" id="person"> </select></body>
Above this code is working fine if we remove the code for "rtype" ID, and entered the hard coded value to the query like this.
var max_adults = 3;
var min_adults = 2;
but we likt to update this value when we change the "rtype" id, the value for the an option is ( 2 3), we just have to split these value in to two part, the higher one will put into " var max_adults", and lower one will go to "var min_adult".
Please give me the proper solution, how can we arrange the codes accordingly.
You need to put the rtype code inside the change event handler tof the #rooms element:
$(function () {
$('#rooms').change(function(){
//get the `#rtype` value
var rtype = $("#rtype").val();
//check to make sure the `#rtype` value isn't an empty string
if (rtype != '') {
var room_num = $(this).val(),
rarray = rtype.split(' '),
options = '',
max_adults = rarray[1],
min_adults = rarray[0];
for (var i = min_adults * room_num; i <= max_adults * room_num; i++) {
options += '<option value="'+i+'">'+i+'</option>';
}
$('#person').html(options);
} else {
//since no `#rtype` value was found alert the user
alert('Please Select a Room Type');
}
//trigger the change event by chaining rather than re-selecting the same element
}).change();
});
Update
To make one element appear when the other changes, add this to the document.ready event handler:
$('#rtype').change(function () {
//if a value has not been selected then hide the `#rooms` element, otherwise show it
if (this.value == '') {
$('#rooms').hide();
} else {
$('#rooms').show();
}
});
You then need to add the following CSS for the #rooms element:
#rooms {
display : none;
}
I have some select boxes like the following:
<select id="my_box1" rel="cal_10">
<option value="A"></option>
</select>
<select id="my_box2" rel="cal_10.50">
<option value="A"></option>
</select>
....
<select id="my_boxn">
<option value="B"></option>
</select>
On changing, I want to add the related value (that is 10 and 10.50) only when the select boxes has the same option value.
For Example: if the first and second select box has option value as A, then I want to add it.
How can I do this using jQuery?
Well, I really can't tell exactly what you're asking, so I'll just guess.
I'm guessing that when a select element receives a change event, we should find all other selects where the selected value is the same, and sum the numeric portion of the rel attribute.
If so, you can do this:
var boxes = $('select[id^="my_box"]');
boxes.on('change', function() {
var n = 0,
val = this.value;
boxes.each(function() {
if( this.value === val ) {
n += +$(this).attr('rel').replace('cal_','');
}
});
alert( n );
});
If you're using a version of jQuery older than 1.7, then use boxes.bind instead of boxes.on.
Something like this, I believe:
$(function() {
$('select#my_box1, select#my_box2').bind('change', function() {
if ($('select#my_box1').val() == $('select#my_box2').val())
$('select#my_box2').append('<option value="10">10</option><option value="10.50">10.50</option>');
else $('select#my_box2').find('option[value="10"], option[value="10.50"]').remove();
});
});
I tried by below code,
$('select').change(function(){
var totalWeight = 0;
var post_array = [];
var actual_val = value;
//alert(actual_val);
var x=0;
$("select").each(function(index, selectedObj) {
current = $(this).val();
var combined = $(this).attr('rel');
if(combined!=undefined)
{
combined = combined.split("_");
var is_combined = combined[0];
var combined_pid = combined[1];
if(actual_val == current && is_combined == "cal"){
post_array[x++] = combined_pid ;
totalWeight+=parseFloat(combined_pid);
}
}
});
alert(totalWeight);
});
I will get my total value in totalWeight