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());
});
Related
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.
I am trying to create radio buttons in a container. The total number of radio buttosn is supplied from the value selected in Combobox that is in another container, when I am trying to do this, I am getting only 1 radio button displayed even the supplied number is more than 1, also I am getting those appended to the previous selection buttons, instead of that I need to clear the contents when the selection is changed and new number of buttons should only be displayed.
$(document).ready(function(){
$("#choice").change(function(){
var radio_name=$("#choice option:selected").text();
var a=$("#choice option:selected").val();
var element=$('<input type="radio" name='+ radio_name +'/><br>');
for(i=1;i <= a;i++){
element.prependTo('#reports');
}
});
});
</script>
</head>
<body>
<div style="padding-top:20px;padding-left: 300px;color: orange;">
Select Your Choice: <select id='choice' style="width:100px;">
<option>Select Your Choice</option>
<option value="4">Sales</option>
<option value="2">Income</option>
<option value="3">Consumer</option>
<option value="5">Exports</option>
</select>
</div>
<div id="reports" style='float: left;padding-top: 100px;color:orange;'>
</div>
element's value can't be duplicated in the HTML.
You need to define element inside the loop, or, since I don't see any use of defining the radios into a variable you can simply do:
$("#choice").change(function(){
$( '#reports' ).empty();
var radio_name=$("#choice option:selected").text();
var a=$("#choice option:selected").val();
for(i=1;i <= a;i++)
$( '<input type="radio" name='+ radio_name +'/><br>' ).prependTo('#reports');
});
empty() is used to clear the container.
Try with the following:
$(document).ready(function(){
$("#choice").change(function(){
var radio_name=$(this).text();
var element=$('<input type="radio" name='+ radio_name +'/><br>');
element.appendTo('#reports');
});
});
Get selected item text
Create new radio element using selected item text
Append new element to reports div
Best Regards,
I saw a few tweaks, like the name needs a [] to make it part of an array. And I think them main problem was that the element object being created was being reused when a new object needed to be created every time.
I tested on jsFiddle to make sure jsFiddle
$(document).ready(function(){
$("#choice").change(function(){
var radio_name=$("#choice option:selected").text();
var a=$("#choice option:selected").val();
for(i=1;i <= a;i++){
$('<input type="radio" name="'+radio_name+'[]" /><br>').prependTo('#reports');
}
});
});
In your for statement you start with i=1; and you tell the function to run until i <= a.
It doesn't matter what positive integer you set the value of a to be it will always be at least equal to if not more than i. So you're only appending once.
I have three (cascading) select tags that appear one after another in a div. The html for them only differ in the options. The name and ids of the select are the same.
<div class="dad">
<select id="foo" name="foo[bar]" value="myVal">
...
<option value="343">boom</option>
...
</select>
<select id="foo" name="foo[bar]" value="myVal">...</select>
<select id="foo" name="foo[bar]" value="myVal">...</select>
</div>
The behavior I need is when a select is changed, an ajax call is made which provides the data (markup) for the next select. The data I get back which is markup a select and it's options is fine but am having issues replacing the next select.
$('select#foo').live("change", function() {
var optionSelected = $('option:selected', this);
var selID = optionSelected.val();
$.post('/postUrl?data=selID', function(data) {
// need to replace the second select
});
...
Usually I would have the id or class of the select I need to replace and would be easy. THe issue here is since all three select have the same id and name how can i identify the select after the one that is selected? Thanks.
You can do something like this..
$('select#foo').live("change", function() {
var optionSelected = $('option:selected', this);
var selID = optionSelected.val();
var nextSelect = $(this).next();
$.post('/postUrl?data=selID', function(data) {
// do action with nextSelect
nextSelect.doSomething;
});
I have a script like this
<script type="text/javascript">
function showSelected(val){
document.getElementById
('selectedResult').innerHTML = "The selected number is - "
+ val;
}
</script>
<div id='selectedResult'></div>
<select name='test' onChange='showSelected(this.value)'>
<option value='1'>one</option>
<option value='2'>two</option>
</select>
The output is shown with
<div id='selectedResult'></div>
So, I want to use this a variable
Actually, I want to get drop down box value with out submit. This script make it, but I can use another suggestions
Thanks
I'm not sure I really understand the question, but if you want to get what's stored in the DIV, use:
var stuff = document.getElementById('selectedResult').innherHTML;
I can suggest you another alternative i think is more useful and you can use it in different way # your project.
In this example you click the options you one and insert them to option list, you can send them from your select name=test if you want, you just need to change it.
DEMO
This is the script you can catch item,links,images,attributes and add them to select box:
$(document).ready(function(){
$('li').on('click',function(){
$('#theSelect').append('<option SELECTED>'+$(this).find('img').attr('value')+'</option>');
var seen = {};
$('option').each(function() {
var txt = $(this).text();
if (seen[txt])
$(this).remove();
else
seen[txt] = true;
});
});
})
$('#del').click(function() {
var $list = $('#theSelect option');
var d = $list.length;
var b=($list.length-1);
$('#theSelect option:eq('+b+')').remove();
});
Most examples I can find showing how to work with attributes show how to set them and not how to retrieve them. In my case, I am trying to get the class of an and then parse it to determine its parent value.
HTML:
<select class='parent' name='parent' size='10'>
<option value='1'>Category 1 -></option>
<option value='2'>Category 2 -></option>
</select>
<select class='child' id='child' size='10'>
<option class='sub_1' value='5'>Custom Subcategory 1.1</option>
<option class='sub_1' value='3'>Subcategory 1.1</option>
<option class='sub_2' value='4'>Subcategory 2.1</option>
</select>
For any given option from the child list, I need to look at the class attribute, parse the name looking for the number (“sub_[n]”) and then grab the value of the option in the parent list.
My code so far (childVal has a value of “5” in my test case):
var class = child.find("option[value=" + childVal + "]").attr("class");
The above class variable is coming back “undefined.” I know the .find is working because I can use it for other things. The problem is getting at the class name.
Once I get the class name, I can strip out the “sub_” to get at the id number.
Is there a better way to do this? Why is .attr(“class”) returning undefined?
Here's a Fiddle link http://jsfiddle.net/n6dZp/8/ to a broken example.
Thank you,
Rick
This is the full function I am working on. It's a cascading select list.
<script type="text/javascript">
function cascadeSelect(parent, child, childVal) {
var childOptions = child.find('option:not(.static)');
child.data('options', childOptions);
parent.change(function () {
childOptions.remove();
child
.append(child.data('options').filter('.sub_' + this.value))
.change();
})
childOptions.not('.static, .sub_' + parent.val()).remove();
if (childVal != '') {
var className = child.find("option[value=" + childVal + "]").attr("class");
** need code here to select the parent and the child options based
on childVal **
}
}
$(function () {
$('.categoryform').find('.child').change(function () {
if ($(this).val() != null) {
$('.categoryform').find('#CategoryId').val($(this).val());
}
});
});
$(function () {
cascadeForm = $('.categoryform');
parentSelect = cascadeForm.find('.parent');
childSelect = cascadeForm.find('.child');
cascadeSelect(parentSelect, childSelect, "5");
});
</script>
class is a reserved word in Javascript, so you can't have a variable with that name. Try
var className = child.find("option[value=" + childVal + "]").attr("class");
Don't use class as a variable name. Kills IE.
This will work but what is child variable equal to?
To obtain the class attribute:
var classAttribute = $('#child').find('option[value="' + childVal + '"]:first').attr('class');
To obtain the 'n' value you can parse the class attribute with a RegEx:
var nValue = /\bsub_([\S]*)\b/.exec( classAttribute )[1];
Hope it helps you.
My apologies, I didn't read your question very carefully at first. Here's my take on what you should do:
var parentVal = $('.child option[value=' + childVal + ']').attr('class').substr(4);
OLD ANSWER
This should do the trick for you:
$(function() {
$('#child').change(function() { $('.parent').val($(this).children(':selected').attr('class').substr(4));
});
});
Here's a live demo: http://jsfiddle.net/n6dZp/
For a start you are missing the $
You need:
var class = $(".child").find("option[value=" + childVal + "]").attr("class");