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");
Related
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());
});
I am creating a form and dynamically populating a field using php so the field value looks like this 01-02-2015-01. I need to prefix the value with a number depending on the value of a select box. So if ( condition ) the prefix will look be 888 so the input value is now 888-01-02-2015-01. I need to do this dynamically so javascript/jQuery is what I need to use. Any help out be appreciated.
Untested code, but probably should work
Html :
<select id='currency'>
<option val='$'>$</option>
<option val='Rs.'>Rs.</option>
</select>
Amount : <input type='text' value='1200' id='amount'/>
Jquery :
$(function(){
$("#currency").change(function(){
var symbol = $(this).val();
var currentValue = $('#amount').val();
$.each(['$','Rs.'],function(i, a){
if(currentValue.indexOf(a)==0){ //if the currentValue starts with any matching symbol, then remove it.
currentValue = currentValue.replace(a,'');
}
});
$("#amount").val(symbol + ' ' + currentValue);
});
//In order to fire change manually, do this
$("#currency").change();
});
Html:
<select id ="combooptions">
<option id="combostart" value=""></option>
</select>
js:
var str = "";
if (combonews.length > 0)
for (var i in combonews) {
str += "<option value='" + combonews[i][0] + "'>" + combonews[i][1] + "</option>";
}
jQuery("#combooptions").append(str);
It works fine, but now I want to remove those appended one, leaving the initial 1 option tag, as shown above.
I tried:
jQuery("#combooptions").html('');
//or
jQuery("#combooptions").append('');
//or
jQuery("#combostart").append('');
//or
jQuery("#combostart").html('');
but no success.
Please help
thank You
Since you gave the first option a unique ID, just do:
$('#combostart ~ option').remove();
What does the "~" (tilde/squiggle/twiddle) CSS selector mean?
To shrink a select list, you can also lower the number of options:
document.getElementById("combooptions").length = 1;
With jQuery:
$("#combooptions")[0].length = 1;
More generic idea to remove "all but the first":
$("#combooptions :not(:first-child)").remove();
Example: http://jsfiddle.net/kVRpy/
You could select all options and then remove the one with id combostart from your selection.
Then call .remove() to remove the unwanted options.
$('#combooptions option').not('#combostart').remove();
Try this:
$('#combooptions').html("<option id='combostart' value=''></option>");
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();
});
I got this example from a blog, but every time I do this:
$(':input[name=' + inputName + ']').each(function(i, selected)
{
alert($(selected).text());
});
I got all an alert with all the options together :(
I have to search by the input name always, the inputs have no id.
Which is the right way to do it?
Kind regards.
That's because select tag is found by jquery, not option tags
This will give you list of the options.
$(':input[name=' + inputName + '] option').each(function(i, selected) {
alert($(selected).text());
});
An example
Assuming your HTML is similar to this
<SELECT NAME="mylist">
<option>Volvo</option>
<option>Saab</option>
<option>Mercedes</option>
<option>Audi</option>
</SELECT>
you need to modify your selector to iterate over the <OPTION> tags, your selector was iterating over the <SELECT> tag
var inputName = mylist;
$(':input[name=' + inputName + '] option').each(function(i, selected) {
alert($(selected).text());
});
Without seeing your html, try this:
$(":input[name='" + inputName + "'] option").each(function(i, selected) {
alert($(selected).text());
});