Traverse to selectMenu and get id (Javascript \ JQuery) - javascript

I want to get the selected value of the inputs.
Only if the ascendent class is a specific one - Q01.
Assume there is no "name" or "ID" on the select menu as i dont know it at run time.
JSFiddle Here
<table>
<TR>
<td class="Q01" valign="MIDDLE"> <b>01.1 </b>Question 01 </td>
<TD>
<SELECT CLASS="selectMenu" ID="" NAME="">
<OPTION VALUE=""><None></OPTION>
<OPTION VALUE="2" SELECTED>2</OPTION>
<OPTION VALUE="1">1</OPTION>
</SELECT>
</TD>
</TR>
<TR>
<td class="Q01" valign="MIDDLE"> <b>01.1 </b>Question 02 </td>
<TD NOWRAP>
<SELECT CLASS="selectMenu" ID="" NAME="">
<OPTION VALUE=""><None></OPTION>
<OPTION VALUE="2">2</OPTION>
<OPTION VALUE="1">1</OPTION>
</SELECT>
</TD>
</TR>
</table>
I have tried $(".Q01:first").next('select').val(); but it returns undefined
EDIT - I changed "input" to "select", my mistake.
ANSWER EDIT - thanks to Hello Cynogenic, i further narrowed it down to what I was after, using "alert($('.Q01:first').next('td').find('select option:selected').val()) i was returned the selected option from the first select menu.

alert($(".Q01:first" ).next('td').children().val());
Check below link :-)
JSFiddle

First off, you have a spare </TD> tag that means your markup is broken.
Assuming you remove the errant tag, this will give you the select element:
$('.q1').next('td').find('select');
You have to traverse the document step by step.
next() means "find the next element within this container, at this level, if it matches the specified selector"
find() means "search the current element for children matching the specified selector"

Related

Remove attribute in all children elements recursively

I have this html:
<tr id="Estuches_1">
<td>
<div class="group">
<input name="VariableDataList[0].VariableDataForLevel[0].ProductionOrderId" id="VariableDataList_0__VariableDataForLevel_0__ProductionOrderId" >
<input name="VariableDataList[0].VariableDataForLevel[0].AggregationLevelConfigurationId" id="VariableDataList_0__VariableDataForLevel_0__AggregationLevelConfigurationId">
<select name="VariableDataList[0].VariableDataForLevel[0].VariableDataId" disabled="disabled" id="VariableDataList_0__VariableDataForLevel_0__VariableDataId">
<option value="00">Serial Shipping Container Code(SSCC-18)</option>
<option value="01" selected="">Global Trade Item Number</option>
<option value="10">Batch or lot number</option>
<option value="11">Production date(YYMMDD)</option>
<option value="17">Expiration date(YYMMDD)</option>
<option value="21">Serial number</option>
</select>
</div>
</td>
<td>
<div class="group">
<input name="VariableDataList[0].VariableDataForLevel[0].Value" disabled="disabled" id="VariableDataList_0__VariableDataForLevel_0__Value">
<span class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="VariableDataList[0].VariableDataForLevel[0].Value"></span>
</div>
</td>
</tr>
In Javascript, I have a var named clone that create with the above html.
I want to remove the attribute disabled in all of the elements in the html (one in the select, and another one in the input text).
I have tried this:
var clone = $($.parseHTML(html));
clone.removeAttribute("disabled");
But it doesn't remove any of them. Maybe, because it is trying to remove the disabled attribute in the tr.
How can I remove the disabled attribute in all of the elements?
The id and the name of the elements will change.
You need to target disabled element using .find() and then use .removeAttr() method
clone
.find('[disabled]') //Target all disabled descendants
.removeAttr('disabled') //Remove disabled

Assigning id to two elements present in a single column

I am facing some issue in assigning id to two elements present in a single column. One element is dropdown and other is a text element. Actually I achieved this in first scenario but i am facing some issues in second scenario. Please help me guys..
Scenario 1:
<td>
<select name="fmeaEntityForm[0].subSystem.id" id="subSystem0" onchange="getsubSystemFunction(this)">
<option value="-1">
<spring:message code="label.fmea.select.subSystem" />
</option>
<c:forEach items="${subSystemList}" var="ss">
<option value="${ss.id}">${ss.subSystem}</option>
</c:forEach>
<option value="0">
<spring:message code="label.fmea.select.other" /></option>
</select>
<input type="text" name="fmeaEntityForm[0].subSystem.subSystem" id="subSystemText0" placeholder="Enter Sub-system if selected other"/>
</td>
In scenario one i can easily access first element by : table.rows[rowCount].cells[cellNumber].childNodes[0] and second element by table.rows[rowCount].cells[cellNumber].lastChild .
Scenario 2: I need to align this dropdown and text box so i used two classes to align both of the elements parallel. Now both elements are aligned properly but I am not able to access both these elements
<td>
<div class="element1">
<select name="fmeaEntityForm[0].subSystem.id" id="subSystem0" onchange="getsubSystemFunction(this)">
<option value="-1">
<spring:message code="label.fmea.select.subSystem" />
</option>
<c:forEach items="${subSystemList}" var="ss">
<option value="${ss.id}">${ss.subSystem}</option>
</c:forEach>
<option value="0">
<spring:message code="label.fmea.select.other" />
</option>
</select>
</div>
<div class="element2">
<input type="text" name="fmeaEntityForm[0].subSystem.subSystem" id="subSystemText0" placeholder="Enter Sub-system if selected other"/>
</div>
</td>
css
.element1
{
display:in-line;
float:left;
}
.element2
{
margin-left:5px;
display:in-line;
float:left;
}
in "scenario 2" use..
table.rows[rowCount].cells[cellNumber].childNodes[0].childNodes[0] to get the select element, and
table.rows[rowCount].cells[cellNumber].lastChild.childNodes[0] to get the input element

How do you reference a checkbox array name value?

I have a sequence of checkboxes and associated select lists. If the checkbox is checked I need to take the value of the corresponding select option and then change the total, but I can't seem to reference this value. Here is a simplified version of the HTML code:
<table>
<tr>
<td>
<input type="checkbox" name="checkboxCK[]" id="checkboxAR1" class="check" />
</td>
<td>
<select name="addonR[]" class="select-colour">
<option value="50">1 ($50)</option>
<option value="100">2 ($100)</option>
<option value="150">3 ($150)</option>
<option value="200">4 ($200)</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="checkboxCK[]" id="checkboxAR2" class="check" />
</td>
<td>
<select name="addonR[]" class="select-colour">
<option value="50">1 ($50)</option>
<option value="100">2 ($100)</option>
<option value="150">3 ($150)</option>
<option value="200">4 ($200)</option>
</select>
</td>
</tr> <tr>
<td>
<input type="checkbox" name="checkboxCK[]" id="checkboxAR3" class="check" />
</td>
<td>
<select name="addonR[]" class="select-colour">
<option value="50">1 ($50)</option>
<option value="100">2 ($100)</option>
<option value="150">3 ($150)</option>
<option value="200">4 ($200)</option>
</select>
</td>
</tr>
<table>
$<span id="theTotalAmount">150</span>
And the javascript code:
$("input.check:checkbox").click(function(){
//run through allcheckboxes that are checked and pull corresponding select option value
for (var i = 0; i < document.getElementsByName('checkboxCK[]').length; i++)
{
//get the value of the selected option
var s = document.getElementsByName('addonR['+i+']');
var theAmount = s.options[s.selectedIndex].value;
console.log(theAmount);
//check the checkbox is checked and if so add the corresponding select value
if(document.getElementsByName('checkboxCK['+i+']').checked)
{
totalCost = totalCost+document.getElementsByName('addonR['+i+']').value;
}
}
//rewrite the html for total amount
document.getElementById("theTotalAmount").innerHTML = totalCost;
});
I am struggling to reference the s variable.. It keeps being undefined. Can anyone see why?
Or is there a better way to achieve what I am trying to do?
The names of the checkboxes don't have a number between the square brackets in the HTML. You shouldn't put one there with your JavaScript.
document.getElementsByName('addonR[]') will give you an (array-like) HTML Collection of all the elements with that name.
Write
var s = document.getElementsByName('addonR[]')[i];

Adding .change to multiple select element

The test case is I've a table in a form. The rows are generated dynamically. Right now with plain html + javascript I've like this,
<tr>
<td>
<select id="brand_1" name="brand[]" onchange="brandChanged(1)">
//some options
</select>
</td>
<td>
<select id="model_1" name="model[]">
<option>Default Value</option>
</select>
</td>
</tr>
<tr>
<td>
<select id="brand_2" name="brand[]" onchange="brandChanged(2)">
//some options
</select>
</td>
<td>
<select id="model_2" name="model[]">
<option>Default Value</option>
</select>
</td>
</tr>
When the brandChanged(x) method is triggered it gets the options from another file with an ajax request and adds them to model_x select element.
Everything is working fine, but my question is how to do it with jQuery? I mean what's the way to bind .change() to these input elements Also I don't like naming ids in name_id way. Is there a better design to solve this?
1) Add a common class to all.
2) remove inline onchange event and write jquery event
3) you can put the value in html5 data attribute:
<select id="brand_1" name="brand[]" class="brand" data-brand="1">
//some options
</select>
<select id="brand_2" name="brand[]" data-brand="2">
//some options
</select>
and write event on class:
$(".brand").change(function() {
var brand = $(this).data("brand");
// do something
});
This may be another approach.
http://jsfiddle.net/thecbuilder/5Lkfh558/
.on() is used because you mentioned trs are generated dynamically.
design implemented without ids
js
$(".mainTable").on("change", ".brand", function () {
var dataFromAjax = callAjax($(this).data("idx"));
$(this).parent().siblings().eq(0).find(".model").html($("<option>DATA from AJAX</option>"));
});

Hide cells depending on select value - generated HTML

I have a problem writing a function to hide two cells depending on the selected value.
The biggest problem is that the HTML is generated and there can be one such select or eight of them. And to make things more interesting, every one of this select is placed in a separate div and while one is shown, others are hidden.
Here is the function I use to toggle cells. Cells can be shown only if selected value is 'Z', otherwise they must be hidden. It works only on the first select while other are completely ignored. I was trying to use .each() function for every element with id="selector" but there was quite a mass with element indexes and it didn't work either.
$("#selector").change(function(){
if($(this).val().trim() == 'Z'){
$("#labelToHide").toggle(true);
$("#selectToHide").toggle(true);
} else {
$("#labelToHide").toggle(false);
$("#selectToHide").toggle(false);
}
});
Here is the working JSFiddle. It might look incomplete, but it is enough to simulate real situation. Bellow is the XML code I work with from which the HTML is generated.
<xh:td class="RightColumn" id="selectToHide">
<form:selectOne ...>
<!-- form code -->
</form:selectOne>
</xh:td>
Is there some way I can make this script work only for currently shown div? Or is there some other workaround?
With the multiple use of IDs it was never going to work as you were doing it. In the following I've changed all the IDs to relevant classes and modified the script to take that into account...
HTML
<div id="divOne">
<table class="gridtable">
<tr>
<td id="allwaysShown">Allways Shown</td>
<td id="allwaysShown">
<select class="selector">
<option value="Z">Z</option>
<option value="X">X</option>
</select>
</td>
<td class="toHide">Hide this</td>
<td class="toHide">
<select>
<option value="Y">Yes</option>
<option value="N">No</option>
</select>
</td>
</tr>
</table>
</div>
<div id="divTwo">
<table class="gridtable">
<tr>
<td id="allwaysShown">Allways Shown</td>
<td id="allwaysShown">
<select class="selector">
<option value="Z">Z</option>
<option value="X">X</option>
</select>
</td>
<td class="toHide">Hide this</td>
<td class="toHide">
<select>
<option value="Y">Yes</option>
<option value="N">No</option>
</select>
</td>
</tr>
</table>
</div>
Javascript
$(".selector").change(function () {
if ($(this).val().trim() == 'Z') {
$(this).closest("tr").find(".toHide").show();
} else {
$(this).closest("tr").find(".toHide").hide();
}
});
What this now does is when a select element (with the class selector) changes, it parses up the DOM to find the row that it is contained in, and then finds all the elements with the class toHide, and either hides or shows them.
Your jsfiddle, modified...
Once you fix the issue with multiple id by changing them to class, you can use the following :
$(".selector").change(function () {
if ($(this).val().trim() == 'Z') {
$(this).parent().nextAll("td").show();
} else {
$(this).parent().nextAll("td").hide();
}
});
$(".selectToHide select").change(function () {
if ($(this).val().trim() == 'Y') {
$(this).parent('td').prev().show();
} else {
$(this).parent('td').prev().hide();
}
});
Updated fiddle
You must use unique ids, use classes instead of ids to group the elements. Instead of toggle use show / hide and assign common class to both select and label e.g. toShowHide and use single call to show hide both. I have changed the html attributes just to demonstrate you should change according to your requirement by keeping in mind that ids must be unique.
Live Demo
$(".selector").change(function () {
if ($(this).val().trim() == 'Z')
$(this).parent().siblings(".toShowHide").show();
else
$(this).parent().siblings(".toShowHide").hide();
});
In HTML id's are all unique, that means on a single page of HTML there can only be one id with the same name, if you have used #selector before, you shouldn't use it again (it won't work in the first place.)
Always use a class for this.
Here's your working code as you needed it
<div id="divOne">
<table class="gridtable">
<tr>
<td class="allwaysShown">Allways Shown</td>
<td class="allwaysShown">
<select class="selector">
<option value="Z">Z</option>
<option value="X">X</option>
</select>
</td>
<td class="hide_this">Hide this</td>
<td class="hide_this">
<select>
<option value="Y">Yes</option>
<option value="N">No</option>
</select>
</td>
</tr>
</table>
</div>
<div id="divTwo">
<table class="gridtable">
<tr>
<td class="allwaysShown">Allways Shown</td>
<td class="allwaysShown">
<select class="selector">
<option value="Z">Z</option>
<option value="X">X</option>
</select>
</td>
<td class="hide_this">Hide this</td>
<td class="hide_this">
<select>
<option value="Y">Yes</option>
<option value="N">No</option>
</select>
</td>
</tr>
</table>
</div>
JQuery
$(".selector").change(function () {
if ($(this).val().trim() == 'Z') {
$(this).closest('tr').find('.hide_this').show();
} else {
$(this).closest('tr').find('.hide_this').hide();
}
});

Categories

Resources