using selector to enable/disable input text with jquery - javascript

Thank "Abhishek Jain", "rps", "adeneo" for your code.
this help me to resolved it.
I have problem with below code:
HTML
<table cellpadding="0" cellspacing="0" width="100%" class="table" id="addtable" border="1">
<thead>
<tr>
<th width="4%"><b>Date</b></th>
<th width="4%"><b>Cut Number</b></th>
<th width="4%"><b>Content</b></th>
<th width="4%"><b>Others</b></th>
<th width="5%"><b>Customer name</b></th>
<th width="4%"><b>Customer code</b></th>
<th width="5%"><b>Address</b></th>
<th width="5%"><b>Owe amount</b></th>
<th width="4%"><b>Executive</b></th>
<th width="6%"><b>Obtain Amount</b></th>
<th width="9%"><b>Obtain Room</b></th>
</tr>
</thead>
<tbody>
<tr id="addrow">
<td><input name="date[]" id="mask_dm1" type="text" size="1" value=""></td>
<td><input name="cutno[]" type="text" size="6" ></td>
<td>
<select name="cutcontent[]" id="selector">
<option value="0">Please select</option>
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
<option value="other">Other</option>
</select>
</td>
<td><input name="cutother[]" type="text" size="4" id="cutother" disabled /></td>
<td><input name="cusname[]" type="text" size="4" ></td>
<td><input name="cuscode[]" type="text" size="2" ></td>
<td><input name="cusaddress[]" type="text" size="4" ></td>
<td><input name="owe[]" type="text" size="2" id="cutowe" disabled /></td>
<td><input name="executive[]" type="text" size="1" /></td>
<td><input name="obtainamount[]" type="text" size="2" id="obtainamount" disabled /></td>
<td><input name="obtainroom[]" type="text" size="2" id="obtainroom" disabled /></td>
</tr>
</tbody>
Javascript:
$(document).ready(function () {
var clonedRow = ' <td><input name="date[]" id="mask_dm1" type="text" size="1" value=""></td>';
clonedRow += ' <td><input name="cutno[]" type="text" size="6" ></td>';
clonedRow += ' <td>';
clonedRow += ' <select name="cutcontent[]" id="selector">';
clonedRow += ' <option value="0">Please select</option>';
clonedRow += ' <option value="1">Value 1</option>';
clonedRow += ' <option value="2">Value 2</option>';
clonedRow += ' <option value="3">Value 3</option>';
clonedRow += ' <option value="other">Other</option>';
clonedRow += ' </select>';
clonedRow += ' </td>';
clonedRow += ' <td><input name="cutother[]" type="text" size="4" id="cutother" disabled /></td>';
clonedRow += ' <td><input name="cusname[]" type="text" size="4" ></td>';
clonedRow += ' <td><input name="cuscode[]" type="text" size="2" ></td>';
clonedRow += ' <td><input name="cusaddress[]" type="text" size="4" ></td>';
clonedRow += ' <td><input name="owe[]" type="text" size="2" id="cutowe" disabled /></td>';
clonedRow += ' <td><input name="executive[]" type="text" size="1" /></td>';
clonedRow += ' <td><input name="obtainamount[]" type="text" size="2" id="obtainamount" disabled /></td>';
clonedRow += ' <td><input name="obtainroom[]" type="text" size="2" id="obtainroom" disabled /></td>';
var appendRow = '<tr id="addrow">' + clonedRow + '</tr>';
$('#btnAddMore').click(function () {
$('#addtable tr:last').after(appendRow);
$('select#selector').change(function () {
var theVal = $(this).val();
switch (theVal) {
case '1':
$('input#cutowe').removeAttr('disabled');
$('input#obtainamount').removeAttr('disabled');
$('input#obtainroom').removeAttr('disabled');
break;
case '2':
$('input#cutother').removeAttr('disabled');
break;
default:
$('input#cutowe').attr('disabled', 'disabled');
$('input#obtainamount').attr('disabled', 'disabled');
$('input#obtainroom').attr('disabled', 'disabled');
$('input#cutother').attr('disabled', 'disabled');
break;
}
});
});
$('select#selector').change(function () {
var theVal = $(this).val();
switch (theVal) {
case '1':
$('input#cutowe').removeAttr('disabled');
$('input#obtainamount').removeAttr('disabled');
$('input#obtainroom').removeAttr('disabled');
break;
case '2':
$('input#cutother').removeAttr('disabled');
break;
default:
$('input#cutowe').attr('disabled', 'disabled');
$('input#obtainamount').attr('disabled', 'disabled');
$('input#obtainroom').attr('disabled', 'disabled');
$('input#cutother').attr('disabled', 'disabled');
break;
}
});
});
When I press "Add more row" button, the selector named "Content" at row#2 has effect on the all input.
how to resolve it?
see example http://jsfiddle.net/N2jyy/6/

Check this;
$(document).ready(function(){
$('#btnAddMore').click(function(){
$('#addtable tr:last').after($('#addtable tr:last').clone());
$('#addtable tr').each(function(){
var currentTR = $(this);
$(this).find('select#selector').change(function(){
var theVal = $(this).val();
switch(theVal){
case '1':
$(currentTR).find('input#cutowe').removeAttr('disabled');
$(currentTR).find('input#obtainamount').removeAttr('disabled');
$(currentTR).find('input#obtainroom').removeAttr('disabled');
break;
case '2':
$(currentTR).find('input#cutother').removeAttr('disabled');
break;
default:
$(currentTR).find('input#cutowe').attr('disabled', 'disabled');
$(currentTR).find('input#obtainamount').attr('disabled', 'disabled');
$(currentTR).find('input#obtainroom').attr('disabled', 'disabled');
$(currentTR).find('input#cutother').attr('disabled', 'disabled');
break;
}
});
});
});
$('#addtable tr').each(function(){
var currentTR = $(this);
$(this).find('select#selector').change(function(){
var theVal = $(this).val();
switch(theVal){
case '1':
$(currentTR).find('input#cutowe').removeAttr('disabled');
$(currentTR).find('input#obtainamount').removeAttr('disabled');
$(currentTR).find('input#obtainroom').removeAttr('disabled');
break;
case '2':
$(currentTR).find('input#cutother').removeAttr('disabled');
break;
default:
$(currentTR).find('input#cutowe').attr('disabled', 'disabled');
$(currentTR).find('input#obtainamount').attr('disabled', 'disabled');
$(currentTR).find('input#obtainroom').attr('disabled', 'disabled');
$(currentTR).find('input#cutother').attr('disabled', 'disabled');
break;
}
});
});
});
Fiddle

After changing the id to class
$(document).ready(function () {
$('#btnAddMore').click(function () {
$('#addtable tr:last').after($('#addtable tr:last').clone(true));
$('select.selector').change(function () {
var theVal = $(this).val();
switch (theVal) {
case '1':
$(this).parents('tr').find('input.cutowe,input.obtainamount,nput.obtainroom').removeAttr('disabled');
break;
case '2':
$(this).parents('tr').find('input.cutowe,input.obtainamount,input.obtainroom,input.cutother').attr('disabled', 'disabled');
break;
}
});
});
});
The above code can be reduced to even more, but this should give you a start on knowing few things, like it is a bad idea to have the same ids and how you can access the other columns from current
http://jsfiddle.net/N2jyy/9/

Change all the duplicate ID's to classes, and use a delegated event handler to handle the change event on the select elements.
What you need to make each select only change the elements withing the same row is context, you'd do that like so:
$('#btnAddMore').on('click', function () {
$('#addtable tr:last').after(appendRow);
});
$('#addtable').on('change', '.selector', function () {
var theVal = $(this).val(),
tr = $(this).closest('tr');
switch (theVal) {
case '1':
$('.cutowe, .obtainamount, .obtainroom', tr).prop('disabled', false);
break;
case '2':
$('.cutother', tr).prop('disabled', false);
break;
default:
$('.cutowe, .obtainamount, .obtainroom, .cutother', tr).prop('disabled', true);
break;
}
});
FIDDLE
I upgraded the jQuery version, and if you're seriously using jQuery 1.3, so should you.

Related

How to change value inside input box that generated by jQuery?

please help me resolved this problem, I have an input value (weight) that generated by jQuery, I know it won't change it's value because of looping in my code, but is there another way to do this ?
The goal is I want to autogenerate the weight input value, but I can change it too.
if the snippet don't work, here's the link :
https://jsfiddle.net/s3grkqxm/
Thank you for your help.
var numRows = 2, ti = 5;
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function recalc() {
var berat = 0;
var qty = 0;
var grandtotal = 0;
var grandtotalbtg = 0;
$('#kas_table').find('tr').each(function() {
var berat = $(this).find('input.berat').val();
var qty = $(this).find('input.qty').val();
var subtotal = (berat * qty);
let berat_max = $(this).find('option:selected').data('berat');
$(this).find('input.subtotal').val(Math.round(subtotal * 100) / 100);
$(this).find('input.berat').val(berat_max).text();
});
}
$(function() {
$('div.table-responsive').on("keyup change blur", recalc);
});
var i=0;
$('#add_new').click(function(){
i++;
$('#mainbody').append('<tr><td>' +
'<select class="form-control nama" name="addmore['+i+'][nama]" id="nama'+i+'" required >' +
'<option disabled="disabled" selected="selected" value="" >Select Produk</option>' +
'<option value="1" data-berat="100">Item 1</option>' +
'<option value="1" data-berat="170">Item 2</option>' +
'</select></td>' +
'<td><input class="form-control qty" type="number" name="addmore['+i+'][qty]" id="qty'+i+'" required ></td>' +
'<td><input step=".001" class="form-control berat" type="number" name="addmore['+i+'][berat]" id="berat'+i+'" required ></td>' +
'<td><input class="form-control subtotal" type="number" name="addmore['+i+'][subtotal]" id="subtotal'+i+'" required readonly></td>'
)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="table-responsive">
<table class="table-bordered" width="100%" id="kas_table">
<thead>
<tr>
<th width="40%">Name</th>
<th width="10%">Qty</th>
<th width="10%">Weight</th>
<th>Subtotal KG</th>
<th>
<button id="add_new" type="button" name="add_new" class="btn btn-sm btn-success"> +</button>
</th>
</tr>
</thead>
<tbody id="mainbody">
<tr>
<td><select class="form-control nama" name="addmore[0][nama]" id="nama0" required >
<option disabled="disabled" selected="selected" value="" >Select Produk</option>
<option value="1" data-berat="100">Item 1</option>
<option value="2" data-berat="170">Item 2</option>
</select></td>
<td><input class="form-control qty" type="number" name="addmore[0][qty]" id=qty0 required></td>
<td><input step=".001" class="form-control berat" type="number" name="addmore[0][berat]" id="berat0" required></td>
<td><input class="form-control subtotal" type="number" name="addmore[0][subtotal]" id="subtotal0" readonly></td>
</tr>
</tbody>
</table>
</div>
the reason when you change Weight it back to the original value is because you refresh the whole table including the drop-down that's why it set back the value which must be set after the dropdown change.$('div.table-responsive').on("keyup change blur", recalc); due this.
you just need to separate each element change event to get the proper results.
I set the value in Weight on the change dropdown by adding this
$(document).on('change', 'select', function() {
$('#kas_table').find('tr').each(function() {
let berat_max = $(this).find('option:selected').data('berat');
$(this).find('input.berat').val(berat_max).text();
});
});
and separately call qty and weight using this
$('.qty').on("keyup change blur", recalc);
$('.berat').on("keyup change blur", recalc);
finally here is your updated code working as expected hope it will helpful for you.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var numRows = 2, ti = 5;
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function recalc() {
var berat = 0;
var qty = 0;
var grandtotal = 0;
var grandtotalbtg = 0;
$('#kas_table').find('tr').each(function() {
var berat = $(this).find('input.berat').val();
var qty = $(this).find('input.qty').val();
var subtotal = (berat * qty);
$(this).find('input.subtotal').val(Math.round(subtotal * 100) / 100);
});
}
function selectProduct(e)
{
let berat_max = $(e).find('option:selected').data('berat');
$(e).parent().parent().find('input.berat').val(berat_max).text();
var berat = $(e).parent().parent().find('input.berat').val();
var qty = $(e).parent().parent().find('input.qty').val();
var subtotal = (berat * qty);
$(e).parent().parent().find('input.subtotal').val(Math.round(subtotal * 100) / 100);
}
$(function() {
$(document).on('change', 'select', function() {
$('.qty').on("keyup change blur", recalc);
$('.berat').on("keyup change blur", recalc);
});
var i=0;
$('#add_new').click(function(){
i++;
$('#mainbody').append('<tr><td>' +
'<select class="form-control nama" name="addmore['+i+'][nama]" id="nama'+i+'" onchange="selectProduct(this)" required >' +
'<option disabled="disabled" selected="selected" value="">Select Produk</option>' +
'<option value="1" data-berat="100">Item 1</option>' +
'<option value="1" data-berat="170">Item 2</option>' +
'</select></td>' +
'<td><input class="form-control qty" type="number" name="addmore['+i+'][qty]" id="qty'+i+'" required ></td>' +
'<td><input step=".001" class="form-control berat" type="number" name="addmore['+i+'][berat]" id="berat'+i+'" required ></td>' +
'<td><input class="form-control subtotal" type="number" name="addmore['+i+'][subtotal]" id="subtotal'+i+'" required readonly></td>'
)
});
});
</script>
</head>
<body>
<div class="table-responsive">
<table class="table-bordered" width="100%" id="kas_table">
<thead>
<tr>
<th width="40%">Name</th>
<th width="10%">Qty</th>
<th width="10%">Weight</th>
<th>Subtotal KG</th>
<th>
<button id="add_new" type="button" name="add_new" class="btn btn-sm btn-success"> +</button>
</th>
</tr>
</thead>
<tbody id="mainbody">
<tr>
<td><select class="form-control nama" name="addmore[0][nama]" id="nama0" onchange="selectProduct(this)" required >
<option disabled="disabled" selected="selected" value="">Select Produk</option>
<option value="1" data-berat="100">Item 1</option>
<option value="2" data-berat="170">Item 2</option>
</select></td>
<td><input class="form-control qty" type="number" name="addmore[0][qty]" id=qty0 required></td>
<td><input step=".001" class="form-control berat" type="number" name="addmore[0][berat]" id="berat0" required></td>
<td><input class="form-control subtotal" type="number" name="addmore[0][subtotal]" id="subtotal0" readonly></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>

Add a string in a <td> using jquery and conditions

What do I want : When the user focus out the field, i would like to add a string in the depending of an other . The are in a table and the problem is that i have to build the string depending of the size of the table.
It would be really nice if you give some documentations to help me because im a bit lost..
HTML :
<table id="tableAssemblage" class="dataAssemblage" style="display: table;">
<thead>
<tr class="entete">
<td>
Type</td>
<td>
Nom</td>
</tr>
</thead>
<tbody>
<td class="centrer">
<select name="typ_element_1" id="typ_element_1"
class="obligatoryAssemblage typ_element">
<option value="" selected="selected"></option>
<option value="EDITION">EDITION</option>
<option value="ENCART">ENCART</option>
<option value="INCARTO">INCARTO</option>
<option value="INCPLUS">INCPLUS</option>
<option value="OPP">OPP</option>
<option value="SUPPLEMENTS" disabled="">SUPPLEMENTS</option>
</select>
</td>
<td class="centrer">
<input type="text" name="nom_element_1" id="nom_element_1" value=""
size="35" length="35" maxlength="35" class="obligatoryAssemblage
nomAssemblage">
</td>
The Table : result in my computer
The jQuery/JS :
$(".nomAssemblage").focusout(function(){
addApresFixNomElement();
});
function addSuffixNomElement(){
// Parametres
var rowCount = $('#tableAssemblage tr').length;
var typElem = $(".typ_element").val();
var nomAss = $(".nomAssemblage").val();
var Suffix;
var id;
// Switch
switch (typElem)
{
case 'EDITION':
for(id=1; id<rowCount; id++){
Suffix = "[EDI ->" + id + "]";
$(".nomAssemblage").append(Suffix);
}
break;
case 'ENCART':
break;
case 'INCARTO':
break;
case 'INCPLUS':
break;
case 'OPP':
break;
case 'SUPPLEMENTS':
break;
}
}
The result i want : This is what i want exaclty
You could use
$("#nom_element_" + id).val($("#nom_element_" + id).val() + " " + Suffix);
as $().append() is to append elements (have also improved the logic as well):
$(".nomAssemblage").focusout(function() {
addSuffixNomElement();
});
function addSuffixNomElement() {
// Parametres
var rowCount = $('#tableAssemblage tbody tr').length;
var typElem = $(".typ_element").val();
var nomAss = $(".nomAssemblage").val();
var Suffix = "";
var id = 1;
// Switch
switch (typElem) {
case 'EDITION':
Suffix = "[EDI ->" + id + "]";
break;
case 'ENCART':
Suffix = "[ENC ->" + id + "]";
break;
case 'INCARTO':
//Suffix = "[INCA ->" + id + "]";
break;
case 'INCPLUS':
//Suffix = "[INCP ->" + id + "]";
break;
case 'OPP':
//Suffix = "[OPP ->" + id + "]";
break;
case 'SUPPLEMENTS':
//Suffix = "[SUP ->" + id + "]";
break;
}
for (id = 1; id < rowCount; id++) {
$("#nom_element_" + id).val($("#nom_element_" + id).val().replace(/\[.*?\]/, '') + " " + Suffix);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tableAssemblage" class="dataAssemblage" style="display: table;">
<thead>
<tr class="entete">
<td>
Type</td>
<td>
Nom</td>
</tr>
</thead>
<tbody>
<tr>
<td class="centrer">
<select name="typ_element_1" id="typ_element_1" class="obligatoryAssemblage typ_element">
<option value="" selected="selected"></option>
<option value="EDITION">EDITION</option>
<option value="ENCART">ENCART</option>
<option value="INCARTO">INCARTO</option>
<option value="INCPLUS">INCPLUS</option>
<option value="OPP">OPP</option>
<option value="SUPPLEMENTS" disabled="">SUPPLEMENTS</option>
</select>
</td>
<td class="centrer">
<input type="text" name="nom_element_1" id="nom_element_1" value="" size="35" length="35" maxlength="35" class="obligatoryAssemblage nomAssemblage">
</td>
<tr>
</tbody>
</table>

Jquery .on(change) event on <select> input only changes first row.

I have a table whereby people can add rows.
There is a select input in the table that when changed, changes the values in a second select field via ajax.
The problem I have is that if a person adds an additional row to the table, the .on(change) event alters the second field in the first row, not the subsequent row.
I've been racking my brain, trying to figure out if I need to (and if so how to) dynamically change the div id that the event binds to and the div that it affects. Is this the solution? If so, could someone please demonstrate how I'd achieve this?
The HTML form is
<form action="assets.php" method="post">
<button type="button" id="add">Add Row</button>
<button type="button" id="delete">Remove Row</button>
<table id="myassettable">
<tbody>
<tr>
<th>Asset Type</th>
<th>Manufacturer</th>
<th>Serial #</th>
<th>MAC Address</th>
<th>Description</th>
<th>Site</th>
<th>Location</th>
</tr>
<tr class="removable">
<!--<td><input type="text" placeholder="First Name" name="contact[0][contact_first]"></td>
<td><input type="text" placeholder="Surname" name="contact[0][contact_surname]"></td>-->
<td><select name="asset[0][type]">
<option><?php echo $typeoption ?></option>
</select></td>
<td><select class="manuf_name" name="asset[0][manuf]">
<option><?php echo $manufoption ?></option>
</select></td>
<td><input type="text" placeholder="Serial #" name="asset[0][serial_num]"></td>
<td><input type="text" placeholder="Mac Address" name="asset[0][mac_address]"></td>
<td><input type="text" placeholder="Name or Description" name="asset[0][description]"></td>
<td><select id="site" name="asset[0][site]">
<option><?php echo $siteoption ?></option>
</select></td>
<td><input type="text" placeholder="e.g Level 3 Utility Room" name="asset[0][location]"></td>
<td><select id="new_select" name="asset[0][contact]"></select></td>
<!--<td><input type="email" placeholder="Email" name="contact[0][email]"></td>
<td><input type="phone" placeholder="Phone No." name="contact[0][phone]"></td>
<td><input type="text" placeholder="Extension" name="contact[0][extension]"></td>
<td><input type="phone" placeholder="Mobile" name="contact[0][mobile]"></td>-->
</tr>
</tbody>
</table>
<input type="submit" value="Submit">
<input type="hidden" name="submitted" value="TRUE" />
</form>
The script I have is
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function() {
var newgroup = $('#myassettable tbody>tr:last');
newgroup
.clone(true)
.find("input").val("").end()
.insertAfter('#myassettable tbody>tr:last')
.find(':input')
.each(function(){
this.name = this.name.replace(/\[(\d+)\]/,
function(str,p1) {
return '[' + (parseInt(p1,10)+1)+ ']'
})
})
return false;
});
});
$(document).ready(function() {
$("#delete").click(function() {
var $last = $('#myassettable tbody').find('tr:last')
if ($last.is(':nth-child(2)')) {
alert('This is the only one')
} else {
$last.remove()
}
});
});
$(document).ready(function() {
$("#myassettable").on("change","#site",function(event) {
$.ajax ({
type : 'post',
url : 'assetprocess.php',
data: {
get_option : $(this).val()
},
success: function (response) {
document.getElementById("new_select").innerHTML=response;
}
})
});
});
</script>
and the assetprocess.php page is
<?php
if(isset($_POST['get_option'])) {
//Get the Site Contacts
$site = $_POST['get_option'];
$contact = "SELECT site_id, contact_id, AES_DECRYPT(contact_first,'" .$kresult."'),AES_DECRYPT(contact_surname,'" .$kresult."') FROM contact WHERE site_id = '$site' ORDER BY contact_surname ASC";
$contactq = mysqli_query($dbc,$contact) or trigger_error("Query: $contact\n<br />MySQL Error: " .mysqli_errno($dbc));
if ($contactq){
//$contactoption = '';
echo '<option>Select a Contact (Optional)</option>';
while ($contactrow = mysqli_fetch_assoc($contactq)) {
$contactid = $contactrow['contact_id'];
$contactfirst = $contactrow["AES_DECRYPT(contact_first,'" .$kresult."')"];
$contactsurname = $contactrow["AES_DECRYPT(contact_surname,'" .$kresult."')"];
$contactoption .= '<option value="'.$contactid.'">'.$contactsurname.', '.$contactfirst.'</option>';
echo $contactoption;
}
}
exit;
}
?>
The code is ugly as sin, but this is only a self-interest project at this stage.
Any assistance would be greatly appreciated.
Cheers,
J.
Working Example: https://jsfiddle.net/Twisty/1c98Ladh/3/
A few minor HTML changes:
<form action="assets.php" method="post">
<button type="button" id="add">Add Row</button>
<button type="button" id="delete">Remove Row</button>
<table id="myassettable">
<tbody>
<tr>
<th>Asset Type</th>
<th>Manufacturer</th>
<th>Serial #</th>
<th>MAC Address</th>
<th>Description</th>
<th>Site</th>
<th>Location</th>
</tr>
<tr class="removable">
<td>
<select name="asset[0][type]">
<option>---</option>
<option>Type Option</option>
</select>
</td>
<td>
<select class="manuf_name" name="asset[0][manuf]">
<option>---</option>
<option>
Manuf Option
</option>
</select>
</td>
<td>
<input type="text" placeholder="Serial #" name="asset[0][serial_num]">
</td>
<td>
<input type="text" placeholder="Mac Address" name="asset[0][mac_address]">
</td>
<td>
<input type="text" placeholder="Name or Description" name="asset[0][description]">
</td>
<td>
<select id="site-0" class="chooseSite" name="asset[0][site]">
<option>---</option>
<option>
Site Option
</option>
</select>
</td>
<td>
<input type="text" placeholder="e.g Level 3 Utility Room" name="asset[0][location]">
</td>
<td>
<select id="new-site-0" name="asset[0][contact]">
</select>
</td>
</tr>
</tbody>
</table>
<input type="submit" value="Submit">
<input type="hidden" name="submitted" value="TRUE" />
</form>
This prepares the id to be incrementd as we add on new elements. Making use of the class, we can bind a .change() to each of them.
$(document).ready(function() {
$("#add").click(function() {
var newgroup = $('#myassettable tbody>tr:last');
newgroup
.clone(true)
.find("input").val("").end()
.insertAfter('#myassettable tbody>tr:last')
.find(':input')
.each(function() {
this.name = this.name.replace(/\[(\d+)\]/,
function(str, p1) {
return '[' + (parseInt(p1, 10) + 1) + ']';
});
});
var lastId = parseInt(newgroup.find(".chooseSite").attr("id").substring(5), 10);
newId = lastId + 1;
$("#myassettable tbody>tr:last .chooseSite").attr("id", "site-" + newId);
$("#myassettable tbody>tr:last select[id='new-site-" + lastId + "']").attr("id", "new-site-" + newId);
return false;
});
$("#delete").click(function() {
var $last = $('#myassettable tbody').find('tr:last');
if ($last.is(':nth-child(2)')) {
alert('This is the only one');
} else {
$last.remove();
}
});
$(".chooseSite").change(function(event) {
console.log($(this).attr("id") + " changed to " + $(this).val());
var target = "new-" + $(this).attr('id');
/*$.ajax({
type: 'post',
url: 'assetprocess.php',
data: {
get_option: $(this).val()
},
success: function(response) {
$("#" + target).html(response);
}
});*/
var response = "<option>New</option>";
$("#" + target).html(response);
});
});
Can save some time by setting a counter in global space for the number of Rows, something like var trCount = 1; and use that to set array indexes and IDs. Cloning is fast and easy, but it also means we have to go back and append various attributes. Could also make a function to draw up the HTML for you. Like: https://jsfiddle.net/Twisty/1c98Ladh/10/
function cloneRow(n) {
if (n - 1 < 0) return false;
var html = "";
html += "<tr class='removable' data-row=" + n + ">";
html += "<td><select name='asset[" + n + "][type]' id='type-" + n + "'>";
html += $("#type-" + (n - 1)).html();
html += "<select></td>";
html += "<td><select name='asset[" + n + "][manuf]' id='manuf-" + n + "'>";
html += $("#manuf-" + (n - 1)).html();
html += "<select></td>";
html += "<td><input type='text' placeholder='Serial #' name='asset[" + n + "][serial_num]' id='serial-" + n + "' /></td>";
html += "<td><input type='text' placeholder='MAC Address' name='asset[" + n + "][mac_address]' id='mac-" + n + "' /></td>";
html += "<td><input type='text' placeholder='Name or Desc.' name='asset[" + n + "][description]' id='desc-" + n + "' /></td>";
html += "<td><select name='asset[" + n + "][site]' class='chooseSite' id='site-" + n + "'>";
html += $("#site-" + (n - 1)).html();
html += "<select></td>";
html += "<td><input type='text' placeholder='E.G. Level 3 Utility Room' name='asset[" + n + "][location]' id='loc-" + n + "' /></td>";
html += "<td><select name='asset[" + n + "][contact]' id='contact-" + n + "'><select></td>";
html += "</tr>";
return html;
}
It's more work up front, yet offers a lot more control of each part. And much easier to use later.

Assign ID to current table row dynamically, tr using jQuery

I need to assign id to specific row in table out of 5 using jQuery function.
I have managed to managed to apply CSS for test purpose but it applying all rows not only the current one
$("#AdditionalTenent").find("tr").css("background-color", "red");
Table structure
<table class="table-bordered">
<thead>
<tr id="AdditionalTenentHeader">
<th>Student UWL ID</th>
<th>Title</th>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr class="AdditionalTenentRecord">
<td><input type="text" value="" name="listedStudentUWLID" id="listedStudentUWLID" class="form-control additionalTententUWLID"></td>
<td><input type="text" value="" name="listedStudentTitle" id="listedStudentTitle" class="form-control listedStudentTitle"></td>
<td><input type="text" value="" name="listedStudentFirstName" id="listedStudentFirstName" class="form-control listedStudentFirstName"></td>
<td><input type="text" value="" name="listedStudentMiddleName" id="listedStudentMiddleName" class="form-control listedStudentMiddleName"></td>
<td><input type="text" value="" name="listedStudentLastName" id="listedStudentLastName" class="form-control listedStudentLastName"></td>
<td><a class="DeleteEntryInline_Icon DeleteAdditionalTenentEntry" href="#"></a></td>
</tr>
<tr class="AdditionalTenentRecord">
<td><input type="text" value="" name="listedStudentUWLID" id="listedStudentUWLID" class="form-control additionalTententUWLID"></td>
<td><input type="text" value="" name="listedStudentTitle" id="listedStudentTitle" class="form-control listedStudentTitle"></td>
<td><input type="text" value="" name="listedStudentFirstName" id="listedStudentFirstName" class="form-control listedStudentFirstName"></td>
<td><input type="text" value="" name="listedStudentMiddleName" id="listedStudentMiddleName" class="form-control listedStudentMiddleName"></td>
<td><input type="text" value="" name="listedStudentLastName" id="listedStudentLastName" class="form-control listedStudentLastName"></td>
<td><a class="DeleteEntryInline_Icon DeleteAdditionalTenentEntry" href="#"></a></td>
</tr>
<tr class="AdditionalTenentRecord">
<td><input type="text" value="" name="listedStudentUWLID" id="listedStudentUWLID" class="form-control additionalTententUWLID"></td>
<td><input type="text" value="" name="listedStudentTitle" id="listedStudentTitle" class="form-control listedStudentTitle"></td>
<td><input type="text" value="" name="listedStudentFirstName" id="listedStudentFirstName" class="form-control listedStudentFirstName"></td>
<td><input type="text" value="" name="listedStudentMiddleName" id="listedStudentMiddleName" class="form-control listedStudentMiddleName"></td>
<td><input type="text" value="" name="listedStudentLastName" id="listedStudentLastName" class="form-control listedStudentLastName"></td>
<td><a class="DeleteEntryInline_Icon DeleteAdditionalTenentEntry" href="#"></a></td>
</tr>
</tbody>
</table>
I have tried following jQuery script but its still applying css to all records in table not the $(this) one!
$("#AdditionalTenent").find(".AdditionalTenentRecord").closest("tr").css("background-color", "yellow");
javaScript Code
$(".additionalTententUWLID").on("change", function () {
var StudentUWLID = $(this).val();
$.ajax({
url: '#Url.Action("GetStudentRecordByID", "StudentProfile")',
type: "POST",
dataType: "JSON",
data: { _GivenStudentUWLID: StudentUWLID },
cache: false
}).done(function (data, textStatus, jqXHR) {
if (data.RecordStatus == "NotAvailable")
{
$(this).MyMessageDialog({
_messageBlockID: "_StatusMessage",
_messageContent: "<div class='warningMessage'> <h4>Given Student Cannot Be Enter As Additional Tenant.</h4> <br/> Student Need to Have their Profile Completed On Student Village Portal Before Can Be Added As Additional Tenant Within The Tendency Form! <br/><br/> Or Enter Correct Student UWL ID "+"</div>",
_messageBlockWidth: "400px"
});
}
else if(data.RecordStatus=="recordFound")
{
alert(data.Response);
var paraedData = JSON.parse(data.Response);
// alert(paraedData.Title + " " + paraedData.FirstName);
// $("#AdditionalTenent").find("tr").css("background-color", "red");
$("#AdditionalTenent").find(".AdditionalTenentRecord").closest("tr").css("background-color", "yellow");
???????????????????
//I need to apply css or ID to row only in use so that in following line I can set values to text field only in single row NOT all of them
$("#AdditionalTenent").find(".listedStudentTitle").val(paraedData.Title);
$("#AdditionalTenent").find(".listedStudentFirstName").val(paraedData.FirstName);
$("#AdditionalTenent").find(".listedStudentMiddleName").val(paraedData.MiddleName);
$("#AdditionalTenent").find(".listedStudentLastName").val(paraedData.LastName);
}
}).fail(function (jqXHR, textStatus, errorThrown) {
alert("error");
});
});
I assume you are using a jQuery click event, if that is the case, you can use:
$(this).closest('tr').remove();
$(".additionalTententUWLID").on("change", function () {
var StudentUWLID = $(this).val();
$(this).attr('id', StudentUWLID);
$.ajax({............my rest of code
and in success response
$("#" + StudentUWLID).closest('tr').css('background-color', 'red');
$("#" + StudentUWLID).closest('tr').find(".listedStudentTitle").val(paraedData.Title);
$("#" + StudentUWLID).closest('tr').find(".listedStudentFirstName").val(paraedData.FirstName);
$("#" + StudentUWLID).closest('tr').find(".listedStudentMiddleName").val(paraedData.MiddleName);
$("#" + StudentUWLID).closest('tr').find(".listedStudentLastName").val(paraedData.LastName);

Display text with conditions on dropdown [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am updating my previous Question:
User has to enter the amounts in text boxes: amt1, amt2, amt3
If they are selecting the option to pay 'Self' value 'S' and they need an Advance payment 'ad' as Yes 'y' then the text box adv1 should display a sum of amt1 + amt2 + amt 3 + $750.
In any other case the value in adv1 should be a 0.00 and of course the text box totalAmt should have the sum always of the amounts always.
I have tried the javascript to get the values of the options onChange and try to evaluate.
However values are not been passed on.
HTML
<table width="800" border="1" cellspacing="0" cellpadding="0">
<tr>
<th>Estimated Travel Cost</th>
<th>AED</th>
<td>
<input name="total" type="text" id "totalAmt"value="" readonly="true" style="text-align:center"/>
</td>
</tr>
<tr>
<th>Amount (AED)</th>
<th>Arranged By</th>
</tr>
<tr>
<td>Arrival (incl Taxes)</td>
<td>
<input name="amt1" id="amt1" type="text" value="0" style="text-align:center"/>
</td>
<td>
<select name = "drop1" id = "str" onChange="updateTextVal()">
<option value="S">Self</option>
<option value="C">Company</option>
</select>
</td>
</tr>
<tr>
<td>Local Travel</td>
<td>
<input name="amt2" type="text" value="" style="text-align:center"/>
</td>
<td>
<select name="drop2">
<option>Self</option>
<option>Company</option>
</select>
</td>
</tr>
<tr>
<td>Accomodation</td>
<td>
<input name="amt3" type="text" value="" style="text-align:center"/>
</td>
<td>
<select name="drop3">
<option>Self</option>
<option>Company</option>
</select>
</td>
</tr>
<td>Estimated Total Cost</td>
<td>
<input name="amt6" type="text" value="" style="text-align:center" />
</td>
<td>
<select name="drop6">
<option>Self</option>
<option>Company</option>
</select>
</td>
</tr>
<tr>
<td>Advance Required</td>
<td>
<select name="advReq" id="ad">
<option value="n">No</option>
<option value="y">Yes</option>
</select>
</td>
<td>
<input name="adv1" type="text" id="adv1" value="0" readonly="readonly" style="text-align:center"/>
</td>
</tr>
</table>
JavaScript
<script>
function updateText() {
var str = this.value;
var $vel = parseInt(document.getElementById("amt1"));
var $el = document.getElementById("adv1");
var val = document.getElementById('ad').value;
var $eval = document.getElementById('str').value;
if(val == 'y'){
if($eval == 's'){
$el.value = "750" + $vel;
} else {
$el.value = "0";
}
}
}
</script>
Html:
<table>
<tr>
<td><input name="amt1" id="txtAmt" type="text" value="" align="left" style="text-align:center" /></td>
<td><select name = "drop1" id="sc"><option value="S">Self</option><option value="C">Company</option></select></td>
</tr>
<tr>
<td>Advance Required</td>
<td><select name="advReq" id="ad">
<option value="y">Yes</option>
<option value="n">No</option>
</select>
</td>
<td><input id='re' name="adv1" type="text" readonly="readonly" value="" /></td>
</tr>
</table>
Javascript
document.getElementById('txtAmt').onkeyup = function(){
var txtV = parseInt(this.value);
var re = document.getElementById('re');
var ad = document.getElementById('ad').value;
var sc = document.getElementById('sc').value;
if(ad == 'y'){
// Yes in Advance Required
if(sc == 'S'){
// Self
re.value = 'Self: ' + (txtV + 750) + '$';
}
else{
re.value = 'Company: ' + (txtV + 750) + '$';
}
}
else{
// No in Advance Required
if(sc == 'S'){
re.value = 'Self: ' + '0.00';
}
else{
re.value = 'Company: ' + '0.00';
}
}
}
Here is demo
You should write a function that gathers the amt1, drop1 and advReq values and sets the appropriate value to adv1.
Then call it when the page is loaded OR the key is released in amt1 OR drop1/advReq select value is changed.
Don't forget that the value in amt1 might be left empty or not be an actual number.
Simply add a onClick function to each of the select elements as onclick="calculateAdvance()" defined as
function calculateAdvance()
{
if(document.forms[0].drop1.getSelectedValue == 'S' && document.forms[0].advReq.getSelectedValue == 'y')
{
var sum = eval(document.forms[0].amt1.value) + 750;
document.forsm[0].amt1.value = sum;
}
}
and change the HTML to
<td><select name = "drop1" onchange="calculateAdvance()"><option value="S">Self</option><option value="C">Company</option></select></td>
and
<select name="advReq" id="ad" onchange="calculateAdvance()">

Categories

Resources