Get value of class with dynamic id jquery - javascript

I have the table bellow and I want to get the input $('.note') value from the id of the previous input :
<tr>
<td><input type="text" id='student_1' class='student'></td>
<td><input type="text" class='note'></td>
</tr>
<tr>
<td><input type="text" id='student_2' class='student'></td>
<td><input type="text" class='note'></td>
</tr>
So it can be something like that :
$(".student").change(function () {
alert(this.id.parent('td input.note').val())
})

You could use this.value or $(this).val() :
$('.classname').on('click',function(){
console.log(this.value, $(this).val(), this.id);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' class='classname' id="id_1" value='value_1'/>
<input type='text' class='classname' id="id_2" value='value_2'/>
<input type='text' class='classname' id="id_3" value='value_3'/>
<input type='text' class='classname' id="id_4" value='value_4'/>
Edit :
Go up to the parent tr using .closest('tr') then search for the related input note using .find('.note') and get the value :
$(".student").on('input', function () {
console.log( $(this).closest('tr').find('.note').val() );
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="text" id='student_1' class='student'></td>
<td><input type="text" class='note' value="1111"></td>
</tr>
<tr>
<td><input type="text" id='student_2' class='student'></td>
<td><input type="text" class='note' value="2222"></td>
</tr>
</table>

You can use a combination of closest and find.
$(".student").on('change', function () {
// the student input to which the change event is bound
var $this = $(this);
// Get the wrapper in which the inputs are present
var $closestTr = $this.closest('tr');
// the input vale that is needed
alert($closestTr.find('.note').val());
});

Yes, you can do this $('#' + this.id).val()
You don't need to include the class in the selector because IDs are unique.

Related

Use index to set value on jquery

Could someone please tell me how I can use the index in this situation?
I have a text field, which is my multiplication factor
<input type="text" id="value">
And I have a table that has 2 fields arranged in the same tr
One with a fixed value
And one that must be the result of multiplying these two values.
Example:
In input I set value = 2
Field Value2 = Value 1 * 2
Value 1
Value 2
3
6
4
8
My jQuery function looks like this:
$( "#btn" ).on( "click", function()
{
let vlUS = $('#value').val()
$("table > tbody > tr > td > input")
.each(function (index) {
let vl1 = $('.val1').val()
let vl2 = vl1 * vlUS
$('.val2').val(vl2)
});
});
Using this way, assigns the same value to all "value2" fields
How can I use index to tune the process?
Loop over the rows and use each row instance to find() the specific inputs within that row
$("#btn").on("click", function() {
let vlUS = $('#value').val();
$("table > tbody > tr").each(function(index) {
const $row = $(this);
let vl1 = $row.find('.val1').val()
let vl2 = vl1 * vlUS
$row.find('.val2').val(vl2);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn">
Calculate
</button> US: <input id="value" value="5" />
<table>
<tr>
<td><input type="text" class="val1" value="3"></td>
<td><input type="text" class="val2"></td>
</tr>
<tr>
<td><input type="text" class="val1" value="6"></td>
<td><input type="text" class="val2"></td>
</tr>
</table>
Consider the following code.
$("#btn").on("click", function() {
$("table tbody tr").each(function(index, elem) {
$(".val2", elem).val(parseInt($(".val1", elem).val()) * parseInt($("#value").val()));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn">Calculate</button> US: <input id="value" value="5" />
<table>
<tr>
<td><input type="text" class="val1" value="3"></td>
<td><input type="text" class="val2"></td>
</tr>
<tr>
<td><input type="text" class="val1" value="6"></td>
<td><input type="text" class="val2"></td>
</tr>
</table>
Simply reduces the operation to one line. Also ensures that if the User enters a Letter; it won't fail.

Find Checkbox in HTML Table Using JQuery Find Method

I have a HTML table which has the following structure:
<table id="myTable">
<tr>
<td><input type="text" name="FullName" value="Tom" /></td>
<td><input type="checkbox" name="isActive" /></td>
<td>Edit
</tr>
</table>
When the user clicks the 'edit' link, a Javascript function is called (see below). In this function I need to get the data from the table, i.e., FullName and whether or not isActive has been checked.
$("#namedTutors").on('click', '.editTutor', function () {
var tr = $(this).closest("tr");
var fullName = tr.find("input[name=FullName]").val();
});
I can get the FullName easy enough, but I'm having difficulties retrieving the data to see if isActive has been checked/ticked or not.
Could someone please help.
Thanks.
You could select the ckeckbox input by name [name=isActive] then use the .is(':checked') to check whether the ckeckbox is checked or not, like:
$("#namedTutors").on('click', '.editTutor', function() {
var tr = $(this).closest("tr");
var fullName = tr.find("input[name=FullName]").val();
var isActive = tr.find("input[name=isActive]").is(':checked');
console.log( isActive );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="namedTutors">
<tr>
<td><input type="text" name="FullName" value="Tom" /></td>
<td><input type="checkbox" name="isActive" /></td>
<td>Edit
</tr>
</table>
if(tr.find('input[name="isActive"]:checked').length) {
console.log('it is checked');
}

Change readonly status of field if radio button selected, no jquery

I have a form, I want to initially have some normal fields and some readonly fields. Then a radio button with two options, if it's the default option nothing changes, if they select the second then the readonly fields become editable.
I need to do this without jquery.
Here's the form
<form name="newstock" action="newstock-save.php" method="post">
<input type="radio" name="individual" value="1" checked> Fruit<br>
<input type="radio" name="individual" value="0"> Veges<br><br>
<table>
<tr>
<td>Item name</td>
<td><input type="text" name="item_name"></td>
</tr>
<tr>
<td>Packing</td>
<td><input type="text" name="packing_name" readonly></td>
</tr>
<tr>
<td>Unit</td>
<td><input type="text" name="packing_unit" readonly></td>
</tr>
</table>
Please assist
First, add the IDs in your HTML.
<form name="newstock" action="newstock-save.php" method="post">
<input type="radio" name="individual" value="1" id="individual1" checked> Fruit<br>
<input type="radio" name="individual" value="0" id="individual0"> Veges<br><br>
<table>
<tr>
<td>Item name</td>
<td><input type="text" name="item_name"></td>
</tr>
<tr>
<td>Packing</td>
<td><input type="text" name="packing_name" id="packing_name" readonly></td>
</tr>
<tr>
<td>Unit</td>
<td><input type="text" name="packing_unit" id="package_unit" readonly></td>
</tr>
</table>
Then, get the elements with getElementById, and add EventListeners in your JS.
const individual1 = document.getElementById("individual1"),
individual0 = document.getElementById("individual0"),
packing_name = document.getElementById("packing_name"),
package_unit = document.getElementById("package_unit");
individual1.addEventListener("change", function(){
packing_name.value = '';
package_unit.value = '';
packing_name.readOnly = true;
package_unit.readOnly = true;
});
individual0.addEventListener("change", function(){
packing_name.readOnly = false;
package_unit.readOnly = false;
});
CodePen: https://codepen.io/anon/pen/vVyVGx
You can remove readonly for an element with the following two options,
Option 1:
document.getElementById('elementId').removeAttribute('readonly');
Option 2:
document.getElementById('elementId').readOnly = false;
Use any of the above code on change of the radio button.
For triggering the click event use the attribute onclick, add the below as an attribute to the input element.
onclick="callBack()"
And inside your JS,
function callBack() {
document.querySelector('input[name="individual"]:checked').value; // get the value and check it with an if condition.
}
Use document.querySelector to get selected radio value based on the value you can disable or enable any I/p field dynamically in JavaScript
For Getting Radio value
document.getElementById(“input[id=‘eleid’]:checked”).value
for enabling / disabling
document.getElementById(elem).disabled = true/false

Adding to a value declared in another function

It is hard to explain, you can see a DEMO HERE
I have a products table that dynamically creates/deletes new lines of products. I also have a totals table that totals up the totals of each line together.
In that totals box, I have a travel box I want to add to the grand total, but the issue I am having is the travel input is outside the table that is totaling all the values. I can replace the total with a new total, but I can not seem to call the sub total, add the travel and output a grand total.
HTML
<table class="order-details">
<tbody>
<tr>
<td><input type="text" value="" name="" placeholder="Work Description" class="wei-add-field description 1"/></td>
<td><input type="text" value="" name="" placeholder="QTY" class="wei-add-field quantity 1" /></td>
<td><input type="text" value="" name="" placeholder="$0.00" class="wei-add-field unit-price 1"/></td>
<td><input type="text" value="" name="" placeholder="$0.00" class="wei-add-field price-total 1" id=""/></td>
<td> </td>
</tr>
</tbody>
</table>
<div class="wei-add-service">Add Item</div>
<table class="wei-add-totals">
<tr>
<td width="50%">Sub Total</td>
<td width="50%" class="wie-add-subtotal"> </td>
</tr>
<tr class="alternate travel">
<td>Travel</td>
<td><input type="text" value="" placeholder="0.00" class="wei-add-field travel" /></td>
</tr>
<tr>
<td>Taxes</td>
<td><input type="text" value="" placeholder="0.00" class="wei-add-field wie-total-taxes" id="wei-disabled" disabled/> </td>
</tr>
<tr class="alternate total">
<td>Total</td>
<td><input type="text" value="" placeholder="0.00" class="wei-add-field wie-grand-total" id="wei-disabled" disabled/></td>
</tr>
</table>
Javascript
var counter = 1;
var testArray = [ 2,3,4,5];
jQuery('a.wei-add-service-button').click(function(event){
event.preventDefault();
counter++;
var newRow = jQuery('<tr><td><input type="text" class="wei-add-field description ' + counter + '"/></td><td><input type="text" class="wei-add-field quantity ' + counter + '" /></td><td><input type="text" class="wei-add-field unit-price ' + counter + '"/></td><td><input type="text" value="" name="" placeholder="$0.00" class="wei-add-field price-total ' + counter + '" id=""/></td><td>X</td></tr>');
jQuery('table.order-details').append(newRow);
});
jQuery('table.order-details').on('click','tr a',function(e){
e.preventDefault();
var table = $(this).closest('table');
jQuery(this).parents('tr').remove();
reCalculate.call( table );
});
jQuery('table.order-details').on("keyup", "tr", reCalculate);
function reCalculate() {
var grandTotal = 0;
jQuery(this).closest('table').find('tr').each(function() {
var row = jQuery(this);
var value = +jQuery( ".unit-price", row ).val();
var value2 = +jQuery( ".quantity", row ).val();
var total = value * value2;
grandTotal += total;
jQuery( ".wei-add-field.price-total", row ).val( '$' + total.toFixed(2) );
});
jQuery(".wie-add-subtotal").text( '$' + grandTotal.toFixed(2));
}
I don't think, given the task of creating this, I would have chosen to do it in the way you did.
However, using your existing code you can bind the Travel value on change, paste, or keyup and run a function on any of those actions. Within that function I have removed the special character ($) from ".wie-grand-total" using a regex and converted the value of ".wie-grand-total" to a float using parseFloat. I also converted the Travel value to a float using parseFloat. I then added them together and made the sum your new value for "wie-grand-total".
/* NEW SINCE COMMENTS */
//Add to your HTML New table
<table class="order-details">
<tbody>
<tr>
<td><input type="text" value="" name="" placeholder="Work Description" class="wei-add-field description 1"/></td>
<td><input type="text" value="" name="" placeholder="QTY" class="wei-add-field quantity 1" /></td>
<td><input type="text" value="" name="" placeholder="$0.00" class="wei-add-field unit-price 1"/></td>
<td><input type="text" value="" name="" placeholder="$0.00" class="wei-add-field price-total 1" id=""/></td>
/* NEW SINCE COMMENTS*/
<td><input type="text" id="travelHid" value=""></td>
<td> </td>
</tr>
</tbody>
</table>
/* NEW SINCE COMMENTS */
$('#travelHid').hide();
var travelVal = 0;
function updateTravelVal(travelVal){
var travelVal = travelVal;
$('#travelHid').val(travelVal);
};
updateTravelVal();
$("#travelVis").bind("change paste keyup", function() {
var noChars = jQuery(".wie-grand-total").val().replace(/[^0-9.]/g, "");
var newTot = parseFloat(noChars) + parseFloat($(this).val());
jQuery(".wie-grand-total").val( '$' + newTot.toFixed(2));
//added error checking
var checkError = jQuery(".wie-grand-total").val( '$' + newTot.toFixed(2));
//if the value that would go in input is NaN then use travelVal
//since there is no value in .wie-grand-total yet
if (typeof checkError !== "string") {
jQuery(".wie-grand-total").val( '$' + travelVal.toFixed(2))
} else if (typeof checkError === "string") {
jQuery(".wie-grand-total").val( '$' + newTot.toFixed(2))
}
/* NEW SINCE COMMENTS */
updateTravelVal(travelVal);
});
A fiddle for demonstration (now with hiddenVal per comment)
http://jsfiddle.net/chrislewispac/wed6eog0/3/
Only potential problems here are it only runs when you change, paste, or key up the value in #TravelVis.
/EXPLAINED SINCE COMMENTS/
It the html I added a td with input. Input id="travelHid". I then make that invisible by applying jQuery method .hide(). I then exposed travelVal to global scope an initiated it with a value of zero then created a function to update that value.
Within that function I set the value to the argument travelVal or to 0 if there are no args. I then immediately call it.
Then, I added a call to that function with the arg travelVal from our bind function to update it if a value is present.
And finally:
Just add a row to the table with preset value of Travel and Quant 1.
http://jsfiddle.net/chrislewispac/xntn7p5p/5/

finding hidden field value above a checked checkbox

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.

Categories

Resources