jquery variable doesn't change on update - javascript

This my problem's semplification. I want to append some text after an input field (on update of the same field), only when the value of a select element is IT.
That's the fields:
<select id="billing_country">
<option value="FR">FR</option>
<option value="IT">IT</option>
</select>
<input type="text" id="woocommerce_cf_piva">
this is the script:
jQuery(document).ready(function () {
var $country_select = jQuery('#billing_country');
// When country change
$country_select.change(function () {
var $country = jQuery('#billing_country option:selected');
$country.each(function() {
FieldCheck(jQuery(this).val());
})
});
function FieldCheck($country) {
var $element = jQuery('#woocommerce_cf_piva');
if ($country == 'IT') {
$element.change(function () {
$element.after($country);
});
}
}
});
You can see this also on jsFiddle
Why it append country name also if i select FR?

It's difficult to understand what you're trying to do with your code.
You want the text input to change its value only if the select box has "IT" selected?
Why are you setting a change handler on the text input?
Why iterate through a select box's options if it's a single select? Just set the text input with the selected option's value, e.g.,
$(function() {
var $billingCountry = $('#billing_country');
$billingCountry.change(function() {
var $country = $('#billing_country option:selected');
fieldCheck($country.val());
});
function fieldCheck(country) {
var $element = $('#woocommerce_cf_piva');
if ($country !== 'IT') {
return;
}
$element.val(country);
}
});
https://jsfiddle.net/davelnewton/w5deffvk/
Edits
Naming conventions changed to reflect typical JS
Non-constructor function names start with lower-case
Non-JQ element vars don't get a leading $
Country value used as guard clause rather than nesting logic
This code is trivial, but nesting can make things harder to reason about

I would add a span and put the text in there so on subsequent change you can fix it:
<select id="billing_country">
<option value="FR">FR</option>
<option value="IT">IT</option>
</select>
<input type="text" id="woocommerce_cf_piva" /><span id="afterit"></span>
Note that this is still pretty verbose:
jQuery(document).ready(function() {
var $country_select = jQuery('#billing_country');
var $element = jQuery('#woocommerce_cf_piva');
// When country change
$country_select.on('change', function() {
var $country = jQuery(this).find('option:selected')[0].value;
var d = ($country == 'IT') ? $country : "";
$element.data('selectedcountry', d);
});
$element.on('change', function() {
var ct = $(this).data('selectedcountry');
//as you have it: $(this).after(ct);// append
// put it in the span to remove/blank out on subsequent changes
$('#afterit').text(ct);
});
});
Here is the total less-verbose version:
$('#woocommerce_cf_piva').on('change', function() {
var v = $('#billing_country').find('option:selected')[0].value;
$('#afterit').text((v == 'IT') ? v : "");
});

You have two problems:
input tag does not have onchange event; you should use onkeydown instead;
you should assign events before if conditions.

If I understand the problem correctly, you want to update input field with the value entered only when drop down selection is "IT". If that is the case, you need to watch input field event and invoke FieldCheck function from with in input field events.

Related

Get value from dynamically created droplist

I my code I create droplists and hidden field for each of them to be able to catch selected value in code behind. I do have a problem set hidden value to the value of selected item in droplist probably because I am not able to create correct selector.
Name of my droplist are dropTypeXXY where XX stands for two alphanumeric characters and Y stands for number for example.
dropTypeU19, dropTypeBB22, dropTypeAG71
hidden fields for them are hdnY where Y stands for number
hdn9, hdn22, hdn71
In both cases these values are IDs of given html elements.
My question is how can I assign list item value to hidden field when droplist selection is changed.
My jQuery
$(document).ready(function(){
$("select[id^='dropType']").on("change",function () {
alert("HI"); //Just to test the selector itself.
});
});
Edit:
My problem is that the selector is not working and alert is not even called. Whey I try to apply similar approach to droplist that I create in code behind it works but not for droplists created by jQuery.
var list = $("<select id = dropType" + response.d[i].TypeId+ i + "/>");
var valueField = $("<input type='hidden' id = 'hdn" + i + "' name ='hdn" + i + "' value=-1 />");
...
$("#<%=grdUsers.ClientID%>").after(list, valueField);
I create them based on AJAX call. I am able to display them in console and display them to user and even give them items but I am not able to run .change() event on them.
Sorry I did not mentioned it earlier.
This doesn't work for them as well. Is there a problem with html tags that are not part of DOM from the beginning of page life?
$("select").on("change", function () {
alert("hi");
});
Edit 2
I looks like my answer lies here. It actually works and alert is raised. Thank you very much guys I'll try to implement the data-target and class trick.
With Dynamically created controls it is easier to select them by class since you cannot use ClientID. Go give them a unique CssClass in code behind when creating the Control.
DropDownList ddl = new DropDownList();
ddl.Items.Insert(0, new ListItem("Value A", "0", true));
ddl.Items.Insert(1, new ListItem("Value B", "1", true));
ddl.CssClass = "DynamicDropDown";
Panel1.Controls.Add(ddl);
Now you can select them with jQuery like this
$(document).ready(function () {
$(".DynamicDropDown").on("change", function () {
alert("HI");
});
})
You can use a class selector ("select" for example) (instead of an id) and add an attribute data-target in your html that say which hidden field is linked to this droplist.
And your js can be something like :
$(document).ready(function(){
$("select.select").on("change",function () {
var $target = $($(this).attr("data-target"));
$target.val($(this).val());
});
});
Or you can also use DOM navigation to find the hidden field without any id if you know the structure of your code and if it's always the same.
Pseudo html code :
<div>
<select>...</select>
<input type="hidden">
</div>
jQuery :
$(document).ready(function(){
$("select").on("change",function () {
var val = $(this).val();
$(this).parent().find("input").val(val);
});
});
You can do it by adding class to a name you specify.
<select id="dropTypeU19" class="cls-name">
<option value="a">a</option>
<option value="a1">a</option>
</select>
<select id="dropTypeBB22" class="cls-name">
<option value="b">a</option>
<option value="b1">a</option>
</select>
<select id="dropTypeAG71" class="cls-name">
<option value="c">a</option>
<option value="c1">a</option>
</select>
<input type="hidden" id="hdn19" />
<input type="hidden" id="hdn22" />
<input type="hidden" id="hdn71" />
<script>
$(function () {
$("select.cls-name").change(function () {
var selectId = $(this).attr("id");
var selectValue = $(this).val();
var hiddenId = "#hdn" + selectId.slice(-2);
$(hiddenId).val(selectValue);
alert($(hiddenId).val());
});
});
</script>
OR:
$("select[id^='dropType']").change(function () {
var selectId = $(this).attr("id");
var selectValue = $(this).val();
var hiddenId = "#hdn" + selectId.slice(-2);
$(hiddenId).val(selectValue);
alert($(hiddenId).val());
});

jQuery: If user changes select to specific option then change different input value

I have a select box like so:
<select id="update_type_picker" name="update_type_picker">
<option value="play">Played</option>
<option value="play">playing</option>
<option value="want">Want</option>
<option value="rating">Rate</option>
</select>
And an input like this:
<input id="playing" name="playing" type="hidden">
And I'm trying to make this jquery work:
$(document).ready(function () {
$("select#update_type_picker").change( function() {
var text = this.text;
if (text = "playing") {
$("input#playing").attr('value', '1');
} else {
$("input#playing").attr('value', '');
}
});
});
I need to use text (not value) because two of the values are the same. With the jquery above the input value changes to 1 regardless of which option I choose. How can I make this work they way I need it to? Thanks!
You have to use:
var text = $(this).find("option:selected").text();
And as mentioned in a comment, you have to use == or === to compare strings in the if, not =.

how to add same onchange events to different select boxes

I want to add 'change' events to 4 select boxes. I have done it using bind().
But I want to call different functions on change of each select box.
Say function1() on change event of SelectBox1...
How should I do it?
I am new to javascript & jquery, so please help.
Thank you
Suppose your HTML like this:
HTML
<select id="selectBox1">
</select>
<select id="selectBox2">
</select>
<select id="selectBox3">
</select>
<select id="selectBox4">
</select>
jQuery
$('select[id^=selectBox]').on('change', function() {
// to get the id of current selectBox
var selectId = this.id;
if(selectId == 'selectBox1') {
function1();
} else if(selecId == 'selectBox2') {
function2();
}
// and so on
});
Some more
$('select[id^=selectBox]').on('change', function() {
// to get the selected value
var value = $.trim( this.value ); // $.trim() used to remove space
// from beginning and end
// you may not use
// to get selected option text
var optText = $('option:selected', this).text()
// to get the selectedIndex
var selIndex = this.selectedIndex;
// OR
var selIndex = $(this).prop('selectedIndex');
});
Note
Here, select[id^=selectBox] get select boxes, whose id start with selectBox. You may have something different id.
.change() used for bind the event to those select box.
Read more about
jQuery selectors
jQuery Events
$.trim()
.prop()
you can set an specific attribute for each select so:
<select id="selectBox1" val='1'>
</select>
<select id="selectBox2" val='2'>
</select>
<select id="selectBox3" val='3'>
</select>
<select id="selectBox4" val='4'>
</select>
and then bind onchange event like this:
$("select").change(function(){
var val = $(this).attr("val");
if (val == '1')
{
//logic for first select change
}
else if (val == '2')
{
//logic for second select change
}
else if (val == '3')
{
//logic for third select change
}
// and so on...
});
hope that helps.

Jquery Javascript HTML selects

So I've got a standard select dropdown. One of the options in the select(the last one) I've got as a text string- var abc.
<select id="exampleselect">
<option>123</option>
<option>xyz</option>
<option>ABC</option>
</select>
var abc = "ABC";
What I'm trying to do is search through the select, find a match against var abc then change the match of var abc to being the selected option.
What I've tried:
//gets all the options from the select
var selectoptions = $('#exampleselect').find('option').text();
//if there is a match of var abc to any of the options in the select
if (selectoptions == abc)
{
//work out how to get the index/eq of the matched element
//put matched element as selected value
$('#exampleselect').val(matchedelementindex);
}
Live example.
As you don't use the value attribute, you can use this code:
var myVar = 'xyz';
$('#exampleselect option').each(function(e) {
var $this = $(this);
if ($this.text() === myVar) {
$this.prop('selected', true);
return false; // stops the iteration
}
});
You could also do it in one line by using the :contains() selector. But this would may not work if you have an option with text "ABC" and another with "ABCD":
$('#exampleselect option:contains('+myVar+')').prop('selected', true);
Although, I would recommend that you add a value attribute to your option elements:
<select id="exampleselect">
<option value="123">123</option>
<option value="xyz">xyz</option>
<option value="ABC">ABC</option>
</select>
this way you can do:
$('#exampleselect').val(myVar);
Try this:
var abc = "ABC";
$("#exampleselect option").each(function() {
if ($(this).text() == abc) {
$(this).attr("selected", true);
return false; // exit each loop
}
})
Or this, although this is slightly less readable:
var abc = "ABC";
$("#exampleselect option").each(function() {
$(this).attr("selected", $(this).text() == abc);
})
This fiddle may help you .
You can achieve this by CSS Selectors which are supported by jQuery
var searched="abc";
$('select option['+searched+']').attr("selected","selected");
http://jsfiddle.net/7EzqU/
// iterate all select options using jquery .each method
$('#exampleselect option').each(function () {
// check if current option text is equal to 'ABC'
if ($(this).text() == 'ABC') {
// get index of option
var index = $('#exampleselect').index($(this))
// set selectedIndex property to change to this option
$('#exampleselect').prop('selectedIndex', index);
}
})
this should do the trick:
http://jsfiddle.net/xXEVw/

Search a dropdown

I have this HTML dropdown:
<form>
<input type="text" id="realtxt" onkeyup="searchSel()">
<select id="select" name="basic-combo" size="1">
<option value="2821">Something </option>
<option value="2825"> Something </option>
<option value="2842"> Something </option>
<option value="2843"> _Something </option>
<option value="15999"> _Something </option>
</select>
</form>
I need to search trough it using javascript.
This is what I have now:
function searchSel() {
var input=document.getElementById('realtxt').value.toLowerCase();
var output=document.getElementById('basic-combo').options;
for(var i=0;i<output.length;i++) {
var outputvalue = output[i].value;
var output = outputvalue.replace(/^(\s| )+|(\s| )+$/g,"");
if(output.indexOf(input)==0){
output[i].selected=true;
}
if(document.forms[0].realtxt.value==''){
output[0].selected=true;
}
}
}
The code doesn't work, and it's probably not the best.
Can anyone show me how I can search trough the dropdown items and when i hit enter find the one i want, and if i hit enter again give me the next result, using plain javascript?
Here's the fixed code. It searches for the first occurrence only:
function searchSel() {
var input = document.getElementById('realtxt').value;
var list = document.getElementById('select');
var listItems = list.options;
if(input === '')
{
listItems[0].selected = true;
return;
}
for(var i=0;i<list.length;i++) {
var val = list[i].value.toLowerCase();
if(val.indexOf(input) == 0) {
list.selectedIndex = i;
return;
}
}
}
You should not check for empty text outside the for loop.
Also, this code will do partial match i.e. if you type 'A', it will select the option 'Artikkelarkiv' option.
Right of the bat, your code won't work as you're selecting the dropdown wrong:
document.getElementById("basic-combo")
is wrong, as the id is select, while "basic-combo" is the name attribute.
And another thing to note, is that you have two variable named output. Even though they're in different scopes, it might become confusing.
For stuff like this, I'd suggest you use a JavaScript library like jQuery (http://jquery.com) to make DOM interaction easier and cross-browser compatible.
Then, you can select and traverse all the elements from your select like this:
$("#select").each(function() {
var $this = $(this); // Just a shortcut
var value = $this.val(); // The value of the option element
var content = $this.html(); // The text content of the option element
// Process as you wish
});

Categories