I am adding values from a select input element to a textarea. How can I then add conditions to this so that if a certain option value is selected, it is always added at the end of all others?
HTML
<p>
<select name="selectfield" id="selectfield">
<option value="" selected>- Select -</option>
<option value="HTML/">HTML/</option>
<option value="CSS/">CSS/</option>
<option value="JQUERY/">JQUERY/</option>
</select>
</p>
<textarea style="width:100%" name="info" id="info" cols="20" rows="5"></textarea>
jQuery
$("#selectfield").on("change", function() {
var $select = $(this);
$("#info").val(function(i, val) {
return val += $select.val();
})
});
In this example, I would like "HTML/" to always be at the end of the textarea regardless of when it is selected.
FIDDLE
When you set the textarea's value, compare what the value of the select is. If it is the string you want to be added at the end, then add it to the end of the value otherwise add it at the beginning.
if($select.val()==="HTML/")
return val = val + $select.val();
else
return val = $select.val() + val;
https://jsfiddle.net/qshcr01a/
Above is smarter but this also works:
$("#selectfield").on("change", function() {
var $select = $(this);
$("#info").val(function(i, val) {
if (val=="HTML/"){
return $select.val()+"HTML/";
}else{
if(val=="JQUERY/HTML/"){
return "CSS/JQUERY/HTML/";
}else if (val=="CSS/HTML/"){
return "JQUERY/CSS/HTML/";
}else{
return val+= $select.val()
}
}
})
});
Related
I have a HTML select list, which can have multiple selects:
<select id="mySelect" name="myList" multiple="multiple" size="3">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option> `
<option value="4">Fourth</option>
...
</select>
I want to get an option's text everytime i choose it. I use jQuery to do this:
$('#mySelect').change(function() {
alert($('#mySelect option:selected').text());
});
Looks simple enough, however if select list has already some selected options - it will return their text too. As example, if i had already selected the "Second" option, after choosing "Fourth" one, alert would bring me this - "SecondFourth". So is there any short, simple way with jQuery to get only the "current" selected option's text or do i have to play with strings and filter new text?
You could do something like this, keeping the old value array and checking which new one isn't in there, like this:
var val;
$('#mySelect').change(function() {
var newVal = $(this).val();
for(var i=0; i<newVal.length; i++) {
if($.inArray(newVal[i], val) == -1)
alert($(this).find('option[value="' + newVal[i] + '"]').text());
}
val = newVal;
});
Give it a try here, When you call .val() on a <select multiple> it returns an array of the values of its selected <option> elements. We're simply storing that, and when the selection changes, looping through the new values, if the new value was in the old value array ($.inArray(val, arr) == -1 if not found) then that's the new value. After that we're just using an attribute-equals selector to grab the element and get its .text().
If the value="" may contains quotes or other special characters that would interfere with the selector, use .filter() instead, like this:
$(this).children().filter(function() {
return this.value == newVal[i];
}).text());
Set a onClick on the option instead of the select:
$('#mySelect option').click(function() {
if ($(this).attr('selected')) {
alert($(this).val());
}
});
var val = ''
$('#mySelect').change(function() {
newVal = $('#mySelect option:selected').text();
val += newVal;
alert(val); # you need this.
val = newVal;
});
or let's play some more
val = '';
$('#id_timezone')
.focus(
function(){
val = $('#id_timezone option:selected').text();
})
.change(
function(){
alert(val+$('#id_timezone option:selected').text())
});
Cheers.
How can I get 2 different variables from select box and hidden inputs in jquery, i.e:
<select name="startID[]" class="startID">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="hidden" name="startText[]" value="Text1">
<br />
<select name="startID[]" class="startID">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="hidden" name="startText[]" value="Text2">
<br />
<select name="startID[]" class="startID">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="hidden" name="startText[]" value="Text3">
so I have 3 select boxes with 3 hidden inputs, how can I get the value of each select boxed and the text that is attached to? i.e: if I select like this:
Select item is 1 and text is Text1
Select item is 3 and text is Text2
Select item is 2 and text is Text3
Thanks in advance
function getValues() {
$('select').each(function (idx, el) {
console.log("Select item is " + $(el).val() + " and text is " + $(el).next('input[type="hidden"]').val());
});
}
If you want to list the values on change:
$('select.startID,input[type="hidden"]').change(getValues);
Demo (modified a bit):
http://jsfiddle.net/6ev9evew/
NOTE
The updates below are not answers for the original question, but the question's author keeps posting extra questions in the comments! So the solution is above!
UPDATE:
As I can understand this is what you looking for:
function getValues() {
var me = this;
$('select').each(function (idx, el) {
console.log("Select item is " + $(el).val() + " and text is " + $(el).next('input[type="hidden"]').val());
if (el === me) return false;
});
}
So basically we stop the loop at the actual element. But it works only if you pass this function to an event handler.
DEMO 2: http://jsfiddle.net/6ev9evew/1/
UPDATE 2:
So, according to the third question, this is a version of the implementation. As I mentioned below in the comments section, there are multiple ways to implement it. This implementation uses that the array indexes are always in order.
function getValues() {
var result = [];
var me = this;
$('select').each(function (idx, el) {
var $el = $(el);
result[10*$el.val()+idx]=("Select item is " + $el.val() + " and text is " + $el.next('input[type="hidden"]').val()+'<br />');
if (me === el) return false;
});
$('#res').html(result.join(''));
}
$('select.startID,input[type="hidden"]').change(getValues);
DEMO 3:
http://jsfiddle.net/6ev9evew/2/
But you can also implement it with array.sort(fn) but than you do a second iteration on the result set.
Anyway if you have more than ten selects in your real code, don't forget to modify the multiplier at result[10*$el.val()+idx] !
If you want to know the value of the changed select (when the user selects a value on any of them) and also get the value of the input type hidden which is next to it, that's the way:
$('.startID').on('change', function () {
var sel = $(this).val();
var hid = $(this).next('input[type=hidden]').val();
console.log('Select item is ' + sel.toString() + ' and text is ' + hid.toString());
});
Demo
UPDATE
To achieve what you've asked in the comments, you can do it like this:
// Create two arrays to store the values.
var sel = [];
var hid = [];
$('.startID').on('change', function () {
// Put the selected values into the arrays.
sel.push($(this).val());
hid.push($(this).next('input[type=hidden]').val());
console.log(sel);
console.log(hid);
for (var i = 0; i < sel.length; i++) {
console.log('Select item is ' + sel[i].toString() + ' and text is ' + hid[i].toString());
}
});
Demo
I have tried to select option based on the textbox text.
Below is my html
<select id="select1">
<option value="">-- Please Select --</option>
<option value="277">12 +$2.99</option>
<option value="278">25 +$2.75</option>
<option value="279">50 +$2.50</option>
<option value="280">100 +$2.00</option>
<option value="281">250 +$1.90</option>
<option value="282">500 +$1.70</option>
<option value="283">1000 +$1.60</option>
<option value="284">2500 +$1.50</option>
<option value="285">5000 +$1.20</option>
<option value="286">10000 +$1.00</option>
<option value="287">25000 +$0.80</option>
</select>
<input type="text" id="pqr" />
And my js like bellow
$(function(){
$('#pqr').change(function(){
$txt = $( "#select1 option:contains('"+$(this).val()+"')" ).text();
$arr = $txt.split(" +");
$( "#select1").val($txt);
alert($arr[0])
$( "#select1" ).filter(function() {
alert($( this ).text > $arr[0]);
})
});
});
so if user enter text 12 or greater than 12 and bellow 25 than i want to select option second 12 +$2.99 and if user enter 1500 than option 1000 +$1.60 get selected. Basically i have try to compare option text before (+) sign and try to select based on that.
Please give me hint or any good help so solve this problem
At every change, iterate over all option elements and compare based on parseInt():
jQuery(function($) {
$('#pqr').on('change', function() {
var value = parseInt(this.value, 10),
dd = document.getElementById('select1'),
index = 0;
$.each(dd.options, function(i) {
if (parseInt(this.text, 10) <= value) {
index = i;
}
});
dd.selectedIndex = index; // set selected option
});
});
Demo
Loop through each option to compare the value. You can use something like this,
$(function () {
$('#pqr').change(function () {
var txtvalue = parseFloat($(this).val());
$("#select1 option").each(function () {
var splitText = $(this).next().text().split("+");
if (splitText.length > 1) {
if (txtvalue < parseFloat(splitText[0].trim())) {
$(this).prop("selected", true);
return false;
}
}
});
});
});
Fiddle
Try this :
$(function(){
$('#pqr').change(function(){
var inputVal = parseInt($(this).val());
$('#select1 option').each(function(){
var firstVal = $(this).text().split('+')[0];
var nextVal = inputVal;
if(!$(this).is(':last'))
$(this).next().text().split('+')[0];
if(parseInt(firstVal) <= inputVal && parseInt(nextVal) >=inputVal)
{
$(this).prop('selected',true);
}
});
});
});
Demo
The $arr[0] in the change callback function will be containing a text value which is not yet parsed to integer so the statement alert($( this ).text > $arr[0]); would not give desired output.
For checking the value lying between a range of select lists option you can use data attributes as followed:
<select id="select1">
<option value="" data-min="-" data-max="-"> Please Select </option>
<option value="277" data-min="12" data-max="25">12 +$2.99</option>
<option value="278" data-min="25" data-max="50">25 +$2.75</option>
This way you will not have to Parse the text of option into integer.
These data values can be retrieved for using jquery data function http://api.jquery.com/data/.
Also all the times you will not be getting the $('#pqr').val() as the text in the option's text so you will have to collect the value of text box and compare it with the range of each option(value >= data-max || value <= data-min).
$(function(){
$('#pqr').on("input", function(){
var text = this.value;
var options = $("#select1 > option");
var elementToSelect = options.eq(0);
if (text.match(/[0-9]+/)) {
elementToSelect = options.filter(function(){
return Number(this.innerText.split("+")[0]) <= text;
})
.eq(-1);
}
elementToSelect.attr("selected",true);
});
});
I am have been searched too much on net but nothing found.
I have 2 select options tag.
I want to show option value in the input tag by multiplying option tag value whatever it is.
and selecting 2nd option tag I want to assign 2nd option tag value to 1st option tag value.
and I also want to multiply that values as the 1st options value have before.
how to do this?
here is my code.
My 1st options tag.
<select name="" id="test">
<option selected="" value="0" disabled='disabled'>Select Duration</option>
<option value="1">1/month</option>
<option value="2">2/month</option>
<option value="3">3/month</option>
<option value="6">6/month</option>
<option value="12">12/month</option>
</select>
<input type="text" data-val="9" id="price_value" style="border:1px solid #0a0; padding:1px 10px; color: #f90;" value="0" size="5"/><br>
Here is 2nd option tag.
<select id="plan">
<option value='Basic'>Basic</option>
<option value='Standard'>Standard</option>
<option value='Professional'>Professional</option>
<option value='Enterprice'>Enterprise</option>
</select>
here is JS.
$('#test').on('change',function(e){
var input = $(this).next('input[type="text"]');
var value = $(this).find('option:selected').val();
input.val( input.data('val') * parseInt(value) );
});
$('#plan').on('change',function(e) {
var plan = $(this).find('option:selected').val();
var price_value = $('#price_value');
if (plan == "Basic") {
price_value.removeAttr('data-val');
price_value.attr('data-val','9');
}
else if (plan == "Standard"){
price_value.removeAttr('data-val');
price_value.attr('data-val','19');
}
else if (plan == "Professional"){
price_value.removeAttr('data-val');
price_value.attr('data-val','29');
}
else if (plan == "Enterprice") {
price_value.removeAttr('data-val');
price_value.attr('data-val','59');
}
});
Here is Demo
Changes
Use $(this).val() instead of $(this).find('option:selected').val() to fetch select value. or even better use this.value
use .data() to set value like price_value.data('val', 9); instead of price_value.attr('data-val','9');
No need to use price_value.removeAttr('data-val');
Code
$('#test').on('change',function(e){
var input = $(this).next('input[type="text"]');
var value = $(this).val(); //Or this.value
input.val( input.data('val') * parseInt(value, 10) );
});
$('#plan').on('change',function(e) {
var plan = $(this).val();
var price_value = $('#price_value');
if (plan == "Basic") {
price_value.data('val',9);
}
else if (plan == "Standard"){
price_value.data('val',19);
}
else if (plan == "Professional"){
price_value.data('val',29);2
}
else if (plan == "Enterprice") {
price_value.data('val',59);
}
$('#test').trigger('change'); //Trigger $('#test') change event
});
DEMO
This solution would work if you are okay with changing your HTML a bit:
<select id="plan">
<option value='9'>Basic</option>
<option value='19'>Standard</option>
<option value='29'>Professional</option>
<option value='59'>Enterprise</option>
</select>
Then simply use:
$('#test, #plan').on('change',function() {
var valueOne = $('#test').val();
var valueTwo = $('#plan').val();
$('#price_value').val(parseInt(valueOne) * parseInt(valueTwo));
});
That's all!
<html>
<script type="text/javascript">
function chkind1(){
var dropdown2 = document.getElementById('dropdown1');
var textbox = document.getElementById('textbox1');
textbox.value=dropdown1.value;
}
</script>
<script type="text/javascript">
function chkind2(){
var dropdown3 = document.getElementById('dropdown2');
var textbox = document.getElementById('textbox2');
textbox.value=dropdown2.value;
}
</script>
<input id="textbox1" name="size" type="text" />
<input id="textbox2" name="copies" type="text" />
<select onchange=chkind1()' id='dropdown1'>
<option value='Nil'>Select Print Size</option>
<option value = '$file - 5x7'>5x7</option>
<option value = '$file - 6x8'>6x8</option>
</select>
<select onchange='chkind2()' id='dropdown2'>
<option value = 'Nil'>Select how many Copies</option>
<option value = '1'>1</option>
<option value = '2'>2</option>
</select>
</html>
Hi all, trying to achieve on the first drop down box (size), is not to overwrite each selection but to append or add each selection one after the other. E.G 5x7, 6x8, etc etc.
I have had a go but can't seem to get it right, could I please have some help on this.
Cheers.
Change your value assignment to append your selection to the current value:
textbox.value += ' ' + dropdown1.value;
Add whatever characters in between the quotes to separate your entries.
UPDATE:
Per question in the comment to remove the value if it is selected again.
if(textbox.value.indexOf(dropdown1.value) == -1) {
textbox.value = textbox.value.replace(dropdown1.value, '');
} else {
textbox.value += ' ' + dropdown1.value;
}
Check to see if the value is contained in the string. indexOf returns -1 if the value is note present. Then you assign the value to be the string with that value removed.
Rather than over-write your previous textbox selection, add to it:
textbox.value += ", " + dropdown1.value;