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);
Related
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.
asigning id for each input tag and select tag in tr depending on query result
I tried a code like this putting an id inside the input tag and select tag
<table id="myTable">
<thead>
<th>Progress</th>
<th>Amount</th>
<th>Action</th>
</thead>
<tbody>
<?php $qry = "SELECT * FROM trade";
foreach($conn->query($qry) as $data){
?>
<form action="update.php" method="post">
<tr>
<td><select name="progress" id="select_progress" onclick="changeSetting()">
<option value="Partial">Partial</option>
<option value="Full">Full</option>
</select></td>
<td><input type="number" name="amount" id="amount"></td>
<td><input type="submit" name="update" value="Update"></td>
<input type="hidden" name="tradeid" value="<?php echo $data['tradeID'];?>">
</tr>
</form>
<?php }?>
</tbody>
</table>
Now i coded the javascript like this:
function changeSetting(){
var selectValue = document.getElementById("select_progress").value;
var amountValue = document.getElementById("amount");
if(selectValue.value === "Partial"){
amountValue.required = true;
}else if(selectValue.value === "Full"){
amountValue.required = false;
}
}
The first row seems to be doing fine, but the second row doesn't apply the javascript i wrote. Any suggestion on how to approach this would be welcome. I know, that an id should be unique for each element but if i have about 50 results in my query i dont know how to place id's on each input and select tag inside my table. Any suggestions or help is greatly appreciated.
All your elements have the same id value, so when you try to getElementById it always returns the first one. One way to work around this is to add the tradeID value to each element's id value to distinguish them. For example:
<td><select name="progress" id="select_progress<?php echo $data['tradeID'];?>" onchange="changeSetting(<?php echo $data['tradeID'];?>)">
<option value="Partial">Partial</option>
<option value="Full">Full</option>
</select></td>
<td><input type="number" name="amount" id="amount<?php echo $data['tradeID'];?>"></td>
<td><input type="submit" name="update" value="Update"></td>
Then you would modify your JS as so:
function changeSetting(id){
var selectValue = document.getElementById("select_progress" + id).value;
var amountValue = document.getElementById("amount" + id);
if(selectValue === "Partial"){
amountValue.required = true;
}else if(selectValue === "Full"){
amountValue.required = false;
}
}
I am an absolute beginner in javascript. I tried to make an table which can save the content i type in it. I just got the total opposite from what i wanted the table deletes the content everytime i refresh the website.
Basically my question is what i have to change so i can save the data permantly and it dont vanish everytime i refresh the webpage. Also it would nice to know what i did wrong. I already tried to change some things but it got just worse
Here is some example code for you:
JS:
$(document).ready(function () {
var counter = 0;
$("#addrow").on("click", function () {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" class="form-control" name="name' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="mail' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="phone' + counter + '"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function (event) {
$(this).closest("tr").remove();
counter -= 1
});
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="price"]').each(function () {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
Basic HTML:
<div class="container">
<table id="myTable" class=" table order-list">
<thead>
<tr>
<td>name</td>
<td>mail</td>
<td>phone</td>
</tr>
</thead>
<tbody>
<tr>
<td class="col-sm-4">
<input type="text" name="name" class="form-control" />
</td>
<td class="col-sm-4">
<input type="mail" name="mail" class="form-control"/>
</td>
<td class="col-sm-3">
<input type="text" name="phone" class="form-control"/>
</td>
<td class="col-sm-2"><a class="deleteRow"></a>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: left;">
<input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" />
</td>
</tr>
<tr>
</tr>
</tfoot>
You can use the localStorage object, which stores data with no expiration date. This data will not be deleted when you refresh the page or even close the browser.
In order to do that, you first need to create the function which will save the data into localStorage.
function save_data(){
let table_data = []
$('.form-control').each(function() { table_data.push( $(this).val() )});
localStorage.setItem('table_data', JSON.stringify(table_data));
}
This function iterates through all table cells and saves its content into table_data array.
Then table_data array is converted into String with JSON.stringify and saved in localStorage.
This function should be executed every time you add, remove or edit one of the rows.
In order to do that we need to create new event handlers:
$('tbody').on("DOMSubtreeModified", function() {save_data()});
$('tbody').on('change', '.form-control', function() {save_data()});
The first one triggers save_data function every time a row is created or removed.
The second one saves data whenever the table's content is modified.
We also need a function for loading data from localStorage:
function load_data(){
let table_data = JSON.parse(localStorage.getItem('table_data'));
for (i = 1; i < table_data.length/3; i++) $("#addrow").click()
$('.form-control').each(function(index) {$(this).val(table_data[index])});
}
This function loads data from localStorage using getItem function.
The loaded data is a String, so it is converted into the array using JSON.parse.
Next, new rows are inserted according to the size of table_data array.
In the end, it iterates through all table cells and fills them with loaded data.
This function should be executed only after you the page is loaded and only if data exists in localStorage.The best way is to put this line at the bottom of ready function:
if (localStorage.getItem("table_data") != null) load_data()
I'm working on dynamically adding new rows and delete new rows with SELECT option. The dynamic row adding and deleting works but the drop down menu doesn't seem to show the JSON array when new row is added. Only the first two static drop down menus shows the JSON array option. Can anyone help figure which part of my code is wrong? Below are my codes and the screenshot:
JavaScript:
<script>
/////////////////ADD and DELETE ROWS///////////////
/************add new row dymnically******************/
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'">'+
'<td>'+
'<select class="pcode" name="project_code[]" >'+
'</select>'+
'</td>'+
'<td><button type="button" name="remove" id="'+i+'" class="btn btn_remove">Delete Row</button></td></tr>');
});
/**************Remove row****************/
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
});
////////////SHOW JSON DATA ON MULTIPLE DROP DOWN MENU/////////////
$(".pcode").each(function() {
$(this).empty();
$(this).append('<option selected="true" disabled>Choose Project Code</option>');
$(this).prop('selectedIndex', 0); //Default Selected Option
const url = 'api_redcap.php'; //JSON Data source
$.getJSON(url, function (data) {
$.each(data, function (key, entry) {
$(".pcode").append($('<option></option>').attr('value', entry.project_code).text(entry.project_code)); // Populate dropdown with list of project code
})
});
});
</script>
HTML code:
<form action="" method="post">
<table id="dynamic_field">
<tr>
<td>
<select class="pcode" name="project_code[]">
</select>
</td>
<td>
</td>
</tr>
<tr>
<td>
<select class="pcode" name="project_code[]">
</select>
</td>
<td>
<button type="button" name="add" id="add">Add Row</button>
</td>
</tr>
</table>
<input type="submit" name="submit" value="submit">
</form>
HTML Screenshot
#Les88, For example I use static array, You can make json call with my bindOption() function and get data from your service call.
You bind the select tag but there is no code written for binding options inside it i modified it so, Kindly look below solution and let me know is it work for you?
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'">'+
'<td>'+
'<select class="pcode" name="project_code[]" >'+
bindOption() +'</select>'+
'</td>'+
'<td><button type="button" name="remove" id="'+i+'" class="btn btn_remove">Delete Row</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$(".pcode").each(function() {
$(this).find('option').remove();
$(this).append(bindOption());
})
});
function bindOption(){
var options = '<option selected="true" disabled>Choose Project Code</option>';
var serviceArray= new Array("Living Room","Dining Room","Bedroom(s)","Family Room","Kitchen","Den","Hallway(s)","Ste(s)","Bathroom","Landing(s)");
for (var i = 0; i < serviceArray.length; i++) {
options += '<option value="' + serviceArray[i] + '">' + serviceArray[i] + '</option>';
}
return options;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
<table id="dynamic_field">
<tr>
<td>
<select class="pcode" name="project_code[]">
</select>
</td>
<td>
</td>
</tr>
<tr>
<td>
<select class="pcode" name="project_code[]">
</select>
</td>
<td>
<button type="button" name="add" id="add">Add Row</button>
</td>
</tr>
</table>
<input type="submit" name="submit" value="submit">
</form>
You can simply achieve this by
$(document).ready(function () {
const url = 'api_redcap.php'; //JSON Data source
function getOptionsHtml() {
var html = '<option selected="true" disabled>Choose Project Code</option>';
$.getJSON(url, function (data) {
$.each(data, function (key, entry) {
html += '<option value="' + entry.project_code + '">' + entry.project_code + '</option>';
})
});
return html;
}
var opionsHtml = getOptionsHtml();
var i = 1;
$('#add').click(function () {
i++;
$('#dynamic_field').append('<tr id="row' + i + '">' +
'<td>' +
'<select class="pcode" name="project_code[]" >' +
opionsHtml+
'</select>' +
'</td>' +
'<td><button type="button" name="remove" id="' + i + '" class="btn btn_remove">Delete Row</button></td></tr>');
});
/**************Remove row****************/
$(document).on('click', '.btn_remove', function () {
var button_id = $(this).attr("id");
$('#row' + button_id + '').remove();
});
$(".pcode").each(function () {
$(this).empty();
$(this).append(opionsHtml);
});
});
I have read through a number of similar questions on stackoverflow but am a little lost of how to modify it to my particular situation. I want to output 2 rows in html differently depending what radio button is selected. I am still learning javascript...
What am i missing please? and how do i get the html to output directly after the radio button form item?
My form looks like this;
<tr>
<td>Select your option</td>
<td><input type="radio" name="your_store" id="store_yes" value="1" onclick = "addrow()" />
<?php echo $text_yes; ?>
<input type="radio" name="your_store" id="store_no" value="0" onclick = "addrow()" />
<?php echo $text_no; ?></td>
</tr>
After this i also have several other form items
At the bottom of the form i have the function;
<script type="text/javascript"><!--
function addrow() {
if(document.getElementById('store_yes').checked) {
html = '<tr>';
html = '<td>Row is showing this</td> ';
html = '</tr>';
} else {
html = '<tr>';
html = '<td>Row is showing something else</td> ';
html = '</tr>';
}
//--></script>
EDIT, if YES is selected the 2 rows appear, the rows need to dissapear again if NO is then subsequently selected, ie change of users mind.
Here is your code, I have used Jquery to append the rows to the end of your table. Read more about .append() in jquery here .
The modified function:
function addrow() {
if (document.getElementById('store_yes').checked) {
$('#yourTable').append('<tr><td>Row is showing this</td></tr>');
} else {
$('#yourTable').append('<tr><td>Row is showing something else</td></tr>');
}
}
The modified HTML
`
<table border="1" id="yourTable"><tr>
<td>Select your option</td>
<td><input type="radio" name="your_store" id="store_yes" value="1" onclick = "addrow()" />
<input type="radio" name="your_store" id="store_no" value="0" onclick = "addrow()" />
</td>
</tr>
</table>
`
Check out the demo here
Update
The demo has been updated to remove appended rows if the user changes his mind