finding hidden field value above a checked checkbox - javascript

I am attempting to return the hidden input field value above a checked checkbox. As it is at the moment I am finding a value of undefined.
This is what I have tried.
var checkedTopics = document.getElementsByName("chkRelatedTopics");
for (var i = 0; i < checkedTopics.length; i++) {
if (checkedTopics[i].checked) {
var uniqueKeyTopic = $(this).parent().
find("input[name=hidTopicsDomain]").val();
console.log(uniqueKeyTopic);
}
}
this is the markup
{{each Items}}
<tr>
<td>
<input type='hidden'
name='hidTopicsDomain' value='${DomainObjectKey}'/>
<input type='checkbox'
name='chkRelatedTopics' value='${subject}'/>
</td>
<td><label id='labRelatedTopicDisplay'>${subject}</label>
</tr>
{{/each}}
How can I retrieve this hidden input field value?
Thanks

Try this:
$('input[type=checkbox]:checked').each(function(){
$(this).prev('input[name=hidTopicsDomain]').val();
});
or if you want to control checked and unchecked then use this:
$('input[type=checkbox]').each(function(){
if($(this).is(':checked')){
//perform something if checked
}
else{
//perform something if not checked.
}
});

You can't use this in the for loop, use .each() and use siblings to find the input
var checkedTopics = document.getElementsByName("chkRelatedTopics");
$(checkedTopics).each(function(){
if (this.checked) {
var uniqueKeyTopic = $(this).siblings("input[name=hidTopicsDomain]").val();
console.log(uniqueKeyTopic);
}
});

Check below if this helps.
http://jsfiddle.net/sandeep605085/28peQ/2/
html:
<table>
<tr>
<td>
<input type='hidden' name='hidTopicsDomain' value='HiddenFieldValue1'/>
<input type='checkbox' checked name='chkRelatedTopics' value='checkbox1'/>
</td>
<td>
<label id='labRelatedTopicDisplay'>label1</label>
</td>
</tr>
<tr>
<td>
<input type='hidden' name='hidTopicsDomain' value='HiddenFieldValue2' />
<input type='checkbox' checked name='chkRelatedTopics' value='checkbox2'/>
</td>
<td>
<label id='labRelatedTopicDisplay'>label2</label>
</td>
</tr>
<tr>
<td>
<input type='hidden' name='hidTopicsDomain' value='HiddenFieldValue3'/>
<input type='checkbox' name='chkRelatedTopics' value='checkbox3' />
</td>
<td>
<label id='labRelatedTopicDisplay'>label3</label>
</td>
</tr>
<tr>
<td>
<input type='button' id='buttonclick' value='Click to Test' />
</td>
</tr>
</table>
js:
$('#buttonclick').click(function(){
var checkedTopics = $('input[name="chkRelatedTopics"]');
checkedTopics.each(function(){
if ($(this).is(':checked')) {
var uniqueKeyTopic = $(this).prev().val();
alert(uniqueKeyTopic);
}
});
});
Thanks.

Related

Get values from HTML only if the checked box is checked (HTML + Python script)

I have a web page with multiple checkboxes and the relative input values
with the following code:
<tr><td><input type=\"checkbox\" id=\"second_checkbox\" name=\"second_checkbox\" value=\"" + Sample_ID + "\"><label for=\""+ Sample_ID + "\">"+ Sample_ID +"</label><br></td><td><select name=\"option\" id=\"option\"><option value=\"\" selected=\"selected\"></option><option value=\"=\">=</option><option value=\"!=\">!=</option><option value=\">\">></option><option value=\">=\">>=</option><option value=\"<\"><</option><option value=\"<=\"><=</option><option value=\"ilike\">contains</option></select></td><td><input type=\"text\" name=\"valore\" placeholder=\"value\"></td></tr>"
and I get the different values by using this functions:
filtri = request.form.getlist('second_checkbox')
simbolo = request.form.getlist('option')
valori = request.form.getlist('valore')
but the array "valori" takes all the empty values on the page and I want to take only the ones that are checked on the first checkbox.
How can I do that?
Thanks
First, remove the duplicate id's and names in the html. An id in html should be unique. Using the right selection mechanism you don't need them either.
For the client side (so, within the browser) you can select all checked checkboxes using the selector [type=checkbox]:checked. Here's a minimal reproducable example.
document.addEventListener(`click`, evt => {
console.clear();
const allChecked = document.querySelectorAll(`[type='checkbox']:checked`);
// ^ only checked
if (allChecked.length) {
return allChecked
.forEach(cb => {
const theRow = cb.closest(`tr`);
console.log(`checked row (#${theRow.rowIndex + 1}) text input value: ${
theRow.querySelector(`input[type='text']`).value || `no value`}`);
});
}
return console.log(`none checked (yet)`);
});
<table>
<tr>
<td>
<input type="checkbox" value="123"> 123
</td>
<td>
selector here
</td>
<td>
<input type="text" placeholder="value" value="row 1">
</td>
</tr>
<tr>
<td>
<input type="checkbox" value="456"> 456
</td>
<td>
selector here
</td>
<td>
<input type="text" placeholder="value" value="row 2">
</td>
</tr>
<tr>
<td><input type="checkbox" value="789"> 789
<td>
selector here
</td>
<td>
<input type="text" placeholder="value" value="row 3">
</td>
</tr>
</table>

How do I get certain vaules of an array in js by checking the checkbox?

I'm new to javascript and kind of stuck with the problem.
I want to create some checkboxes and when I select and submit some of them, I want to get the associated output from an array. In my case, I can only send some data by hard coding in the "value" attribute of the "input" element. But, I want to send the data from the array "names".
Can anyone please help me out?
function submit() {
var names = ["zihan", "zihan", "zihan", "masud", "masud", "shakil"];
var arrayNAME = [];
var tblName = document.getElementById("tblName");
var check = tblName.getElementsByTagName("input");
for (var i = 0; i < check.length; i++) {
if (check[i].checked) {
arrayNAME.push(check[i].value);
}
}
if (arrayNAME.length > 0) {
alert(`Selected value: ${arrayNAME.join(",")}`);
}
}
<table id="tblName">
<tr>
<td>
<input type="checkbox" id="zahid" value="zahid">
<label for="zahid"> Zahid </label>
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="masud" value="masud">
<label for="masud"> Masud </label>
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="jihan" value="jihan jihan jihan">
<label for="jihan"> Jihan </label>
</td>
</tr>
</table>
<br>
<button onclick="submit()"> Submit </button>
You may select all the checkboxes and then depending on their index in the page and if a checkbox is checked append the desired value to the final array from "names" array.
function submit() {
// dummy values to facilate the recognition of the checked input(s)
const names = ['checkbox one', 'checkbox two', 'checkbox three'],
arrayNAME = [],
tblName = document.getElementById("tblName"),
check = tblName.querySelectorAll("input[type=checkbox]");
// push the "names" values to "arrayNAME" of the checked inputs
check.forEach((el, idx) => el.checked && arrayNAME.push(names[idx]));
// for a better UX on the site (SO), I'd use "console.log" instead of "alert"
arrayNAME.length && console.log(`Selected value: ${arrayNAME.join(",")}`);
}
<table id="tblName">
<tr>
<td>
<input type="checkbox" id="zahid" value="zahid">
<label for="zahid"> Zahid </label>
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="masud" value="masud">
<label for="masud"> Masud </label>
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="jihan" value="jihan jihan jihan">
<label for="jihan"> Jihan </label>
</td>
</tr>
</table>
<br>
<button onclick="submit()"> Submit </button>

How do I locate elements in the same row as another in a dynamic table?

I am making a page that contains a table with a button to add a row. It is a table for users to input data, and will eventually be submitted to a database.
Currently, I have a price and a quantity field in each row. When either of them change, I want to calculate the total and write it to another cell.
This is my event handler (wrapped in $(document).ready()):
$(".quantity_input, .price_input").change(function () {
console.log(this.value);
cal_total();
});
This is my current code:
function cal_total() {
if (isNaN(parseFloat(this.value))) {
alert("You must enter a numeric value.");
this.value = "";
return;
}
var cell = this.parentNode;
var row = cell.parentNode;
var total = parseFloat($("#items_table tr").eq(row.index).find("td").eq(3).find("input").first().val()) * parseFloat($("#items_table tr").eq(row.index).find("td").eq(4).find("input").first().val());
if (!isNaN(total)) {
$("#items_table tr").eq(row.index).find("td").eq(5).html(total.toFixed(2));
}
}
And this is what the inputs look like:
<input type='text' class='fancy_form quantity_input' name='quantities[]' size='4' style='text-align:center;border-bottom:none;'>
In addition to my original question, the event is never fired. Can anyone see why?
But more importantly, is this the best way to retrieve the values? I really don't think so but I cant come up with anything more clever.
Thank you!
you have to pass paremeter to calc_total to define input or tr
try this code
$(".quantity_input, .price_input").change(function () {
$(".quantity_input, .price_input").change(function () {
cal_total(this);
});
});
function cal_total(elem){
var row=$(elem).closest("tr")
var quantity=row.find(".quantity_input").val()-0
var price=row.find(".price_input").val()-0
var total=quantity * price
row.find(".totl_input").val(total)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input class="quantity_input" />
</td>
<td>
<input class="price_input" />
</td>
<td>
<input class="totl_input" />
</td>
</tr>
<tr>
<td>
<input class="quantity_input" />
</td>
<td>
<input class="price_input" />
</td>
<td>
<input class="totl_input" />
</td>
</tr>
<tr>
<td>
<input class="quantity_input" />
</td>
<td>
<input class="price_input" />
</td>
<td>
<input class="totl_input" />
</td>
</tr>
</table>

Grab a certain table row

I have a table with a radio button per row.
<table id="t1">
<tr><td><input type="radio" onclick="grab_row()" value=1></td><td>Data1<td>Data11</td></tr>
<tr><td><input type="radio" onclick="grab_row()" value=2></td><td>Data2<td>Data22</td></tr></table>
I would like to have a function that grabs the values of the row selected via radio.
my function:
function grab_row () {
var radio = $("input[name=t1]:checked").val();
}
The function only grabs the radio id that is currently selected.
for example, if the first radio is clicked, Data1 and Data11 are returned.
Thanks
Here's my interpretation of what you're looking for
html
<table>
<tr>
<td>
<input type="radio" value="1" name="myradio" />
</td>
<td>Data1</td>
<td>Data11</td>
</tr>
<tr>
<td>
<input type="radio" value="2" name="myradio" />
</td>
<td>Data2</td>
<td>Data22</td>
<td>Data222</td>
</tr>
js
$("input:radio[name=myradio]").click(function () {
var myvals = [];
var elem = $(this).parent().next();
while (elem.prop("tagName") == "TD") {
myvals.push(parseInt(elem.html().substring(4)));
elem = elem.next();
}
console.log(myvals);
});
I assumed that you just need the integers after the "Data" string, but you can grab the entire content of the TD element with just the .html() and leaving out the .substring(4)
fiddle
When you use .val() when using a selector that returns multiple elements, it will only return the value of the first element. Instead, you need to iterate through them using .each().
var values = [];
$("input[name=t1]:checked").each(function(idx, val) {
//spin through and collect each val
values.push($(val).val());
})
console.log(values); //view values in console
This should be your jQuery:
$("input[type=radio]").click(function () {
console.log($(this).val());
});
and this should be your HTML:
<table id="t1">
<tr>
<td>
<input type="radio" name="foo" value="1" />
</td>
<td>Data1</td>
<td>Data11</td>
</tr>
<tr>
<td>
<input type="radio" name="foo" value="2" />
</td>
<td>Data2</td>
<td>Data22</td>
</tr>
</table>
jsFiddle example
Note that you can also use $("input[name=foo]") instead of $("input[type=radio]").

how can I sum selected checkbox(s) row values?

I have a table in asp.net mvc . in this table I have a checkbox for every row . I want when I check a checkbox find wage value in that row and sum with other rows wages that checked .
I want to do this sum via Jquery or java script .
#foreach (var item in Model)
{
<tr id="rowid">
<td>
<input type="checkbox" name="chk-#intCount" id="chk-#intCount" class="chkclass" />
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.TechnicalNo)
</td>
<td class="sum" id="wagein">
#Html.DisplayFor(modelItem => item.Wage)
</td>
<td class="sum" id="time">
#Html.DisplayFor(modelItem => item.Time)
</td>
</tr>
}
this is my code in asp.net mvc . how can I sum checked values in wage and time now ?
EDIT :
My jQuery code :
<script src="/Scripts/jquery-1.4.4.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.chkclass').click(function() {
var sum = 0;
$('.chkclass:checked').each(function() {
sum += parseFloat($(this).closest('tr').find('.wagein').text());
});
$('#sum').html(sum);
});​
});
</script>
my html code :
<tr>
<td>
<input type="checkbox" name="chk-1" id="chk-1" class="chkclass" />
</td>
<td class="sum wagein">
10
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="chk-2" id="chk-2" class="chkclass" />
</td>
<td class="sum wagein">
10
</td>
</tr>
any idea ?! what is the problem ?!
Start by fixing your markup as it is highly broken. Remember that ids must be unique throughout your entire HTML document:
#foreach (var item in Model)
{
<tr>
<td>
<input type="checkbox" name="chk-#intCount" id="chk-#intCount" class="chkclass" />
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.TechnicalNo)
</td>
<td class="sum wagein">
#Html.DisplayFor(modelItem => item.Wage)
</td>
<td class="sum">
#Html.DisplayFor(modelItem => item.Time)
</td>
</tr>
}
then you could subscribe to the .click() event of the checkboxes and accumulate a sum for all wages:
$(function() {
$('.chkclass').click(function() {
var sum = 0;
$('.chkclass:checked').each(function() {
sum += parseFloat($(this).closest('tr').find('.wagein').text());
});
alert(sum);
});
​});
And here's a live demo to see it in action: http://jsfiddle.net/pbkjr/
Ok, starting with the markup you have shown, correctly wrapped with <table></table> tags, with a div below to show the total:
<table>
<tr>
<td>
<input type="checkbox" name="chk-1" id="chk-1" class="chkclass" />
</td>
<td class="sum wagein">
10
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="chk-2" id="chk-2" class="chkclass" />
</td>
<td class="sum wagein">
10
</td>
</tr>
</table>
<div id="total"></div>
The following jquery (which #Darin wrote) will sum all the checked rows when any checkbox is clicked:
$('.chkclass').click(function() {
var sum = 0;
$('.chkclass:checked').each(function() {
sum += parseFloat($(this).closest('tr').find('.wagein').text());
});
$('#total').html(sum);
});
This is very close to Darin's original, except that I have changed the last line to output the total to the div with id total. This seems more likely than writing the sum to every row!
This can be seen in this live example: http://jsfiddle.net/ADE3a/
jQuery(document).ready(function ($) {
var sum = 0;
$('input[type=checkbox]').click(function () {
sum = 0;
$('input[type=checkbox]:checked').each(function () {
sum += parseFloat($(this).closest('div').find('.payment').val());
});
$('#total').val(sum);
});
});
Darin Dimitrov
Thanks a ton. I was having a issue where I wanted do addition of hidden fields for checked check boxes and pass the checkbox value(true or false) to the controller.
#Html.CheckBoxFor was creating a hidden field right next to it for each checkbox
I was using $(this).next().val() this was giging me NAN issue. since it was getting the value of the hidden field.
Thanks you to your post I was able to get the next div hidden field value
I did something like below

Categories

Resources