On button click same row checkbox should be checked - javascript

I have placed a button and checkbox at end of each row of the table. I want now is that if I click button in row 1 then checkbox only in row 1 gets checked and so on. code is working fine if I go from 1st to last row turn by turn.
Problem occurs if I click directly on for eg. 2nd row. if I click in 2nd row then the checkbox in 1st row is selected.
I have tried matching the ids of button and checkbox control but that is not possible as the name in id will always be different.
cols += '<td><button type="button" class="btn btn-info btn-sm btn-block" onclick="req_ser()" id="check_btn' + limit + '" value="' + data + '">Request</button></td>';
cols +='<td><input type="checkbox" class="chec" id="check' + limit + '" value="' + data + '" disabled="disabled"></input></td>';
function req_ser() {
var sl_num = [];
var count = 0;
for (var bv = 0; bv <= limit; bv++) {
var stai;
var bvv = bv + 1;
var cls = document.getElementsByClassName("btn btn-info btn-sm btn-block");
var chs = document.getElementsByClassName("chec")
cls[bv].id = "check_btn" + (bv + 1);
chs[bv].id = "check" + (bv + 1);
alert(cls[bv].id);
alert(chs[bv].id);
//stai = $('#check' + bvv + '').on(':click');
//stai = $('#check' + bvv + '').is(':clicked');
//stai = $('#check' + bvv + '').data(':clicked', true);
$('#check' + bvv + '').prop('checked', true);
stai = $('#check' + bvv + '').is(':checked');
if (stai == true) {
sl_num.push({
"serial": document.getElementById("slnchk" + bvv + "").innerText,
});
break;
}
}
expected result is whichever row button I click only that row checkbox should be checked. Please guide regarding this.

You can do it with .closest() and .find() in jquery.
Example:
$('td .btn').on("click", function() {
$(this).closest('tr').find('.chec').prop("checked", true);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td><button type="button" class="btn btn-info btn-sm btn-block">Request</button></td>
<td><input type="checkbox" class="chec" disabled="disabled"></td>
</tr>
<tr>
<td><button type="button" class="btn btn-info btn-sm btn-block">Request</button></td>
<td><input type="checkbox" class="chec" disabled="disabled"></td>
</tr>
<tr>
<td><button type="button" class="btn btn-info btn-sm btn-block">Request</button></td>
<td><input type="checkbox" class="chec" disabled="disabled"></td>
</tr>
</table>

It's not too difficult with just vanilla JS:
A click listener calls the checkit function.
Inside the function, all the code is wrapped in an if block so it only runs if the clicked element is one of the buttons (which, in this case, are identified by the checkBtn class).
The function automatically has access to the event that triggered it. We refer to this argument as event for ease of reading.
The event's target property gives us the button that was clicked.
From there, we get the closest ancestor element with the tagName TR, and we call it row.
Within this row, we get all the input elements, take the first one, and call it checkbox.
To this checkbox, we add the attribute "checked" (with an empty string as its value).
Note: The lines that are commented out would let the user toggle the "check" by clicking again.
document.addEventListener("click", checkit);
function checkit(event){
if(event.target.classList.contains("checkBtn")){
const row = event.target.closest("TR");
const checkbox = row.getElementsByTagName("INPUT")[0];
//if(checkbox.checked){ checkbox.removeAttribute("checked"); }
//else{
checkbox.setAttribute("checked", "");
//}
}
}
<table>
<tr>
<td><button class="checkBtn">Click me</button></td>
<td><input type="checkbox" value="one" /></td>
</tr>
<tr>
<td><button class="checkBtn">Click me</button></td>
<td><input type="checkbox" value="two" /></td>
</tr>
</table>
Alternatively (and if speed is not a concern), you can add a separate eventListener to each button as you create it. In this case, the if condition would be unnecessary.
This code could be shorter but the example is more explicit for the sake of clarity.

Related

Data Attribute Access from Dynamically Added Select

So far I have only seen examples getting data attribute from a select option that is already on the page, or added after a few seconds.
I'm looking at clicking a button, adding 3+ form fields which the one searchable dropdown field has a data tag in it with other information to use. Maybe I'm not going about it the right way.
This is the generated options on the select
while ($row = mysqli_fetch_array($result))
{
$part = mysqli_real_escape_string($link, $row['part_number']);
$output .= "<option value=" .$row['id']. " data-sellprice=".$row['sell_price'].">" .$part. "</option>";
}
This is the Javscript that is creating the fields.
<script>
$(document).ready(function(){
$(document).on('click', '.add', function(){
var html = '';
html += '<tr>';
html += '<td><select name="item_name[]" class="form-control fstdropdown-select item_name" id="swoparts"><option value="">Select Unit</option><?php echo fill_unit_select_box($db); ?></select></td>';
html += '<td><input type="text" name="item_quantity[]" class="form-control item_quantity" /></td>';
html += '<td><input type="text" name="item_price[]" class="form-control item_price" /></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
setFstDropdown();
});
$(document).on('click', '.remove', function(){
$(this).closest('tr').remove();
});
$("#swoparts").on("change", "select[name='item_name[]']", function(){
console.log(this.value);
})
});
</script>
I would like to get the data-sellprice from the option and display it in the item_price[] text field and use the amount to to keep adding to the other amounts of the form for a total.
I can make the data attribute work on a select that is already on the page when loaded.
EDITED PART NEED HELP HERE!!!!!!
I have gotten this far, please explain on what I have done and why its not working. I can make this all work for the select that created during the page creation or on document load. I CAN NOT make this work after the fact.
<table class="table table-bordered" id="item_table">
<tr>
<th>Enter Item Name</th>
<th>Enter Quantity</th>
<th>Item Price</th>
<th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
</tr>
<tr>
<td>
<select id="swoparts" class="swoparts">
<option value="1" data-sellprice="55.00">Some thing we sell</option>
<option value="2" data-sellprice="100.00">Something else we sell</option>
</select>
</td>
<td><input type="text"></td>
<td><input type="text"><td>
</tr>
</table>
$(document).ready(function(){
$('select.swoparts').change(function() {
var e = document.getElementById("swoparts");
var strUser = e.options[e.selectedIndex].value
console.log(strUser);
});
$(document).on('click', '.add', function(){
$("#item_table").last().append('<td><select id="swoparts" class="swoparts"><option value="1" data-sellprice="55.00">Some thing we sell</option><option value="2" data-sellprice="100.00">Something else we sell</option></select></td><td><input type="text" name="item_quantity[]" class="form-control item_quantity" /></td><td><input type="text" name="item_price[]" class="form-control item_price" id="sell_price" /></td><td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>');
});
WHY can't I grab the information from the dynamically generated select?
I want 3 boxes added to my table, with a dropdown that is filled from a database where I can grab the dataset attribute and show it somewhere else and add it together with other dataset attributes from other added table rows.
I have created a fiddle:
Add Select box having option where data-* attribute is there.
Then on change of the these select box value find the selected option
Fetch the above option's data-* attrbite and add it.
https://jsfiddle.net/asutosh/k6jxmgs9/21/
The JS code below:
function addFields() {
const form1 = document.querySelector('#testform')
const selectField = document.createElement('select');
let dataView = null;
[1, 2, 3].forEach((aVal) => {
let optionElem = document.createElement('option');
optionElem.setAttribute("value", aVal);
optionElem.setAttribute("data-sellprice", "sell-" + aVal);
optionElem.text = aVal;
selectField.appendChild(optionElem);
})
selectField.addEventListener('change', () => {
form1.querySelectorAll('option').forEach((opt) => {
if (opt.value === selectField.value) {
dataView = opt.getAttribute("data-sellprice");
}
})
document.querySelector('#selectdData').innerHTML = dataView;
});
form1.appendChild(selectField);

add dynamic order to add remove html input field

i have this code for add/remove dynamic input:
JS:
$(function () {
$("#btnAdd").bind("click", function () {
var div = $("<tr />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$("body").on("click", ".remove", function () {
$(this).closest("tr").remove();
});
});
function GetDynamicTextBox(value) {
var number = Math.random();
return '<td id="' + number + '"><input name = "DynamicTextBox" type="text" value = "' + value + '" class="form-control" /></td>' + '<td><select name="" class="form-control"><option> Select</option><option> Male</option><option> Female</option></select></td>' + '<td><input name = "DynamicTextBox" type="radio" value = "' + value + '" /></td>' + '<td><input name = "DynamicTextBox" type="checkbox" value = "' + value + '" /></td>'+'<td><input name = "order" type="number" value = "" /></td>' + '<td><button type="button" class="btn btn-danger remove"><i class="fas fa-times"></i></button></td>'
}
HTML:
<p> </p>
<h5 class="text-center">Dynamic Control : Text Box, Dropdown List, Radiobox and Checkbox</h5>
<section class="container">
<div class="table table-responsive">
<table class="table table-responsive table-striped table-bordered">
<thead>
<tr>
<td>TextBox</td>
<td>Dropdown List</td>
<td>Radio</td>
<td>CheckBox</td>
<td>Order</td>
<td>BTN</td>
</tr>
</thead>
<tbody id="TextBoxContainer">
</tbody>
<tfoot>
<tr>
<th colspan="5">
<button id="btnAdd" type="button" class="btn btn-primary" data-toggle="tooltip" data-original-title="Add more controls"><i class="fas fa-plus"></i> Add </button></th>
</tr>
</tfoot>
</table>
</div>
</section>
this code work true for me but how do can i add dynamic order(from 1 to ...) for each row(td). my mean add order input from number 1 and add +1 number from last order number.
demo is here
update: (my need)
You need to just modify the JS code logic. The below example shows the use of variable count and its usage.
Here, the variable count is declared as 1 initially and as per the "Add" click the count value has been incremented by 1. Same way the count is been decremented by 1 when we are deleting/removing the the "tr" column.
$(function () {
var count = 1;
$("#btnAdd").bind("click", function () {
var div = $("<tr />");
div.html(GetDynamicTextBox("", count));
$("#TextBoxContainer").append(div);
count++;
});
$("body").on("click", ".remove", function () {
$(this).closest("tr").remove();
count--;
});
});
The click function will have one more argument count which is used for the rendering/displaying of the count value in the order field.
function GetDynamicTextBox(value, count) {
var number = Math.random();
return '<td id="' + number + '">
<input name = "DynamicTextBox" type="text" value = "' + value + '" class="form-control" />
</td>' + '
<td>
<select name="" class="form-control">
<option> Select</option>
<option> Male</option>
<option> Female</option>
</select>
</td>' + '
<td>
<input name = "DynamicTextBox" type="radio" value = "' + value + '" />
</td>' + '
<td>
<input name = "DynamicTextBox" type="checkbox" value = "' + value + '" />
</td>'+'
<td>
<input name = "order" type="number" value = "' + count + '" /></td>' + '
<td>
<button type="button" class="btn btn-danger remove"><i class="glyphicon glyphicon-remove-sign"></i></button>
</td>'
}
The above code works when we are removing the row from the last column.
If you are removing in-between the row from the list of tr tags you will find the order columns values are not arranged properly.
The below code is used for the removing the tr tag in-between the row and as well as the from the last tr tag. This code will be flexible for removing the tr row from anywhere in the list as well as updating the order row in the incremental way.
$("body").on("click", ".remove", function () {
var deleteElement = $(this).closest("tr");
var countOfDeleteElement = $(deleteElement).find("#order").val();
var lastElementCount = count - 1;
if (countOfDeleteElement !== lastElementCount) {
// It will come inside this if block when we are removing inbetween element.
var remainingElements = deleteElement.nextAll('tr'); // get all the below elemnts from the removing element.
// updating all remainingElements value of the order column
remainingElements.each((i, ele) => {
$(ele).find("#order").val(countOfDeleteElement);
countOfDeleteElement++;
})
}
deleteElement.remove();
count--;
});

Validate form using Jquery with border and blur effects

I wish to validate a simple table form using jquery. So far I have a for loop that loops through all the fields and checks if they are empty. Then I have another for loop that checks to see if the age is within a certain range. And finally, the last loop checks to see if the email is in the correct RegEx pattern.
Currently only the first loop is working while the others are not being looped through. I have tried to do console.logs and it confirmed that the other loops are not being touched. Any ideas or help would be appreciated!
Semi working Code pen: https://codepen.io/anon/pen/ZXVmQz?editors=1010
Code:
HTML
<section class="container">
<div class="table table-responsive">
<table class="table table-responsive table-striped table-bordered" id="data-table">
<thead>
<tr>
<td>Name</td>
<td>Age</td>
<td>Email</td>
</tr>
</thead>
<tbody id="TextBoxContainer">
</tbody>
<tfoot>
<tr>
<th colspan="5">
<button id="btnAdd" type="button" class="btn btn-primary" data-toggle="tooltip" data-original-title="Add more controls"><i class="glyphicon glyphicon-plus-sign"></i> Add </button></th>
</tr>
</tfoot>
</table>
</div>
JQuery
function validate(input) {
var isValid;
var filter = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
var email = $('.email').val();
var length = $('.data').length;
console.log($('.email').val());
var rowInputLength = $("#TextBoxContainer input").length;
for (var i=0; i<rowInputLength; i++) {
if (!($(input[i]).val() == "" )) {
isValid = true;
validBorder($(input[i]));
if ($('input[type=number]') && !($(input[i]).val()<= 2 || $(input[i]).val() >= 100)) {
isValid = true;
console.log($('#age').val());
validBorder($(input[i]));
}
if ('$(input[i][type=email])' && filter.test(email)) {
isValid = true;
validBorder($(input[i]));
}
}
else {
isValid = false;
invalidBorder($(input[i]));
}
}
return isValid;
}
How the table is created
function GetDynamicTextBox(value1, value2, value3) {
return '<td><input name = "DynamicTextBox" id="name" type="text" value = "" placeholder = "' + value1 + '" class="form-control data" /></td>' +
'<td><input name = "DynamicTextBox" id="age" type="number" min="3" max="100" value = "" placeholder = "' + value2 + '" class="form-control data" /></td>' +
'<td><input name = "DynamicTextBox" id="email" type="email" value = "" placeholder="' + value3 + '" class="form-control data email" /></td>' +
'<td><button type="button" class="btn btn-danger remove"><i class="glyphicon glyphicon-remove-sign"></i></button><button type="button" class="btn btn-success edit"><i class="glyphicon glyphicon-ok"></i></button></td>';
}
When this button is pressed:
$(function () {
$("#btnAdd").bind("click", function () {
var div = $("<tr />");
div.html(GetDynamicTextBox("Enter Name", "Enter Age", "Enter Email"));
$("#TextBoxContainer").append(div);
$('#btnAdd').attr("disabled", "disabled");
$(".data").blur(function() {
validate($(this))
});
});
});
You lacked the relevant piece of code in the question, had to find it in your pen.
In your anonymous "Add Row" function you need to call validation with all of the input fields, using the selector you attempted to use can be done like so:
validate( $( ".data" ) )
Also other issues found in validate method: $(input[i]).val() is a string, convert it to a number using prefix +, +$(input[i]).val()

How to set name value of dynamic adding input ? javascript jquery

I have a web page for applying. In this web page, rows are dynamic add after addp button clicked.I can add new row successfully with addPf() method. And these input name attribute should be enName0, enName1, enName2....., but it works fail with name="enName"+aDWI.
Here is my html code:
<div>
<table>
<tr>
<td>
<input type="button" id="addP" onclick="addPf()" value="addPeople">
</td>
</tr>
<tr>
<td>
new row added in here;
</td>
</tr>
</table>
</div>
Here is my javascript code:
<script>
var aDWI=0;
function addPf()
{
newrow = '<tr><td><input style="width:98%" name="enName"+aDWI></td></tr>';
$(newrow).insertAfter($('#staTable tr:eq('+aDWI+')'));
aDWI = aDWI + 1;
}
</script>
name="enName"+aDWI is not right.I have no idea about this, who can help me ?
Change from
newrow = '<tr><td><input style="width:98%" name="enName"+aDWI></td></tr>';
to
newrow = '<tr><td><input style="width:98%" name="enName'+aDWI+'"></td></tr>';
The issue is because you need to concatenate the variable in the string correctly, using the ' character.
Also note that you should really be using unobtrusive event handlers instead of the outdated on* event attributes. In addition, you can simplify the logic by using jQuery's append(), like this:
var aDWI = 0;
$('#addP').click(function() {
newrow = '<tr><td><input style="width:98%" name="enName' + aDWI + '" value="' + aDWI + '"></td></tr>';
$('#staTable').append(newrow);
aDWI = aDWI + 1;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<table id="staTable">
<tr>
<td>
<input type="button" id="addP" value="addPeople">
</td>
</tr>
<tr>
<td>
new row added in here;
</td>
</tr>
</table>
</div>
Just update it with
<script>
var aDWI=0;
function addPf()
{
newrow = '<tr><td><input style="width:98%" name="enName'+aDWI+'"></td></tr>';
$(newrow).insertAfter($('#staTable tr:eq('+aDWI+')'));
aDWI = aDWI + 1;
}
</script>

jQuery on function is getting bound to the container, why so?

I have a simple jquery code
$('tbody').on("click",$('vote'+rowCount),function(){alert('hi');});
but the alert shows up when i click anywhere on the table body instead of just showing up on clicking the selector
Why is this happening?
----Edit---
Got it working by writing the element as "#vote"+rowCount instead of writing as $('vote'+rowCount)
But there is another weird problem -
I am creating dynamic rows with this code, but whatever i type in the value of the textbox remains empty (as initialized), why so
$('#add_ans').click(function(){
var rowCount = $('table tbody tr').length + 1;
var rowString = '<tr>\
<td><div class="span_5"><span class="badge badge-success">'+rowCount+'</span></div></td>\
<td><div class="span3"><input type="text" class="input-large" value="" /></div></td>\
<td><div class="span2 pull-right"><b>0</b></div></td>\
<td><div class="span2"><button class="btn btn-success" id="vote'+rowCount+'"><b>Vote!</b> <i class="icon-thumbs-up"></i></button></div></td>\
<td><div class="span2"><button class="btn btn-info" disabled><b>Reviews</b> <i class="icon-ok-circle"></i></button></div></td>\
</tr>'
$('tbody').append(rowString);
$('tbody').on("click","#vote"+rowCount,voteOption);
});
and the event handler is
function voteOption(){
var rowCount = $('tr').index($(this).closest('tr'));
alert(rowCount);
var ans = $('tr:eq('+rowCount+') .input-large').attr('value');
alert(ans);
}
This is because the second argument is selector (string), not an element selected by $().
$('vote'+rowCount) is not correct and the .on() click event will be fired anywhere you click because the .on event is actually bind to the <tbody>.
For example, this will match the <div> inside the <tbody> and bind the click event to it.
$('tbody').on("click", 'div' ,function(){alert('hi');});
Here is the code example....
HTML
<input type="button" id="createBtn" value="Create"/>
<table id="mytable">
<tbody id="mytableBody">
</tbody>
</table>
JavaScript
$(document).ready(function()
{
var i = 0;
$("#createBtn").click(function()
{
var newRow = $("<tr></tr>").attr("id", "row"+i);
var btn = $("<button>Vote</button>").attr("id", "vote"+i);
var col = $("<td><span>Video "+i+"</span></td>");
col.append(btn);
newRow.append(col);
$("#mytable tbody").append(newRow);
i++;
});
$('#mytable tbody').on("click", "button", function(){
alert(this.id);
if(this.id == 'vote0')
{
alert("Thanks for voting for video 0.");
}
else if(this.id == 'vote1')
{
alert("Thanks for voting for video 1.");
}
else
{
// handle the rest....
}
});
});
You can also find this in jsfiddle http://jsfiddle.net/33Wny/1/

Categories