I have this, simplified for testing, architecture :
<div class="container">
<div class="row" id="row_0">
<div class="col-md-12">
<form id="form_0">
<select name="test1" id="test1_0"></select>
<select name="test2" id="test2_0"></select>
<input name="test3" id="test3_0"/>
</form>
</div>
</div>
</div>
And my goal is to clone that row in the container, while changing EVERY _0 and incrementing it by 1.
I'm able to clone a the row, get the numeric value of the row and create another row with an incremented id.
var div = $('div[class^="row"]:last');
var num = parseInt( div.prop("id").match(/\d+/g), 10 ) +1;
var clone = div.clone().prop('id', 'row_'+num );
div.after( clone );
But I have no idea how to change each and every id that has a _0 to _1, can anyone help me please?
Fiddle exemple : https://jsfiddle.net/L5mn63g7/1/
var $row = $('.row').last(); //Select the row
var num = parseInt($row.attr('id').match(/\d+$/)[0]) + 1; //get the current index
var clone = $row.clone(); //clone the row
clone.attr('id', 'row_' + num); //change its id
clone.children('[id]').each(function() {//go through all elements with an id
$(this).attr('id', $(this).attr('id').replace(/\d+$/, num)); //change the id
});
clone.appendTo('body'); //append the result to the body (replace 'body' with where you want it)
This code has not been tested, it might contain bugs or errors.
However I agree with Rory McCrossan :
You could just place each row in a div with a specific id, then call insider classes with var $row = $('#div_id'); $row.find('.class') (I'm using this for an included form)
var div = $('div[id^="row"]:last');
var num = parseInt( div.prop("id").match(/\d+/g), 10 ) +1;
var clone = div.clone().prop('id', 'row_'+num );
clone.find('[id]').each(function(){var $this = $(this); $this.prop('id', $this.prop('id').split('_')[0] + '_' + num);});
div.after( clone );
Related
I am trying to remove an item every time it is clicked on but only a single item at a time (the item that was clicked on) when trying to make a 'to-do' list. I can easily remove all simultaneously but I am having a lot of issues trying to do it at an individual level. I thought this would work but hoping to get a second set of eyes on it.
var toDoCount = 0;
var todoarray = [];
window.onload = function() {
//user clicked on the add button in the to-do field add that text into the to-do text
$('#add-to-do').on('click', function(event) {
event.preventDefault();
//assign variable to the value entered into the textbox
var value = document.getElementById('to-do').value;
//test value
console.log(value);
var todoitem = $("#to-dos");
todoitem.attr("item-");
//prepend values into the html and add checkmark, checkbox, and line break to make list
var linebreak = "<br/>";
var todoclose = $("<button>");
todoclose.attr("data-to-do", toDoCount);
todoclose.addClass("checkbox");
todoclose.text("☑");
//prepend values to html
$("#to-dos").prepend(linebreak);
$("#to-dos").prepend(value);
$("#to-dos").prepend(todoclose);
toDoCount++;
todoarray.push(value);
console.log(todoarray);
//to remove item from checklist
$(document.body).on("click", ".checkbox", function() {
var toDoNumber = $(this).attr("data-to-do");
$("#item-" + toDoNumber).remove();
});
});
}
HTML is below
<div class ="col-4">
<!-- To Do List -->
<form onsubmit= "return false;">
<span id = "todo-item" type = "text">
<h4>Add your Agenda Here</h4>
<input id ="to-do" type = "text">
<input id ="add-to-do" value = "Add Item" type = "submit">
</span>
</form>
<div id="to-dos"></div>
</div>
don't need the number, just the element.
change...
$("#item-" + toDoNumber).remove();
to...
$(this).remove();
e.g.
$(document.body).on("click", ".checkbox", function() {
$(this).remove();
});
I have the following code
<tr val='question'>
<td>
<input style='width: 500px' type='text' placeholder='Q.Enter your question here for radio button? '>
</tr>
How can i find the value of input box embedded in cell .
function saveUserDefQues(){
var table=document.getElementById("QuestionList");
var surveyquestionform=document.forms[0];
var count=$('#QuestionList tr').length
for (var i = 0; i<count; i++) {
var row = table.rows[i];
if(row.getAttribute('val')==='question')
{
var Cells = row.getElementsByTagName("td");;
}
}
}
document.querySelector('tr[val] > td > input').value;
Array.from(document.querySelectorAll('tr[val] > td > input')).forEach(function(entry, index, entries)
{
entry.value; // you may store the value OR process with it AS you see fit
});
Since you are using Jquery this can be done this way.
replace this line of code
var Cells = row.getElementsByTagName("td");
with
var Cells = $(row).find('td');
var inputValue = Cell.find('input').val(); // gives you value of input
Code Refactoring recommended
I would like to refactor your code as below
HTML
<tr data-val='question'> // use data-* attribute to add custom attributes into tags
<td>
<input style='width: 500px' type='text' placeholder='Q.Enter your question here for radio button? '>
</td> // close your td
</tr>
Script
function saveUserDefQues(){
var surveyquestionform = document.forms[0]; // not sure what this is for, so ill leave it as is.
$('#QuestionList tr[data-val="question"]').each(function(){ //loop all tr's which has the data-val set to question
var inputValue = $(this).find('td input').val(); //get the value of input
console.log(inputValue);
});
}
$("tr[val='question'] > td > input").val()
But first you need to write a valid HTML. </td> closing tag is missing. Also you need to put this tr in a <table>.
See this Plunker
function getResult(){
$( "tr" ).each(function( index ) {
console.log($(this).find('input').attr('placeholder') );
});
}
I'm currently trying to add a jQuery function to a row of radio buttons. The problem is that I need to add dynamically many rows. Now For this example I only added 2 elements into the array of newNodes, but in my application newNodes can potentially have many different sizes.
So basically I want to add the Query function something like this:
$('#rowID input').on('change', function() {
alert($('input[name=i]:checked', '#rowID').val());
});
Where it exists inside the forloop and is added for each new row. "rowID" is a variable assigned to the unique row identifier and then use the loop iterator "i" as a way to distinguish the radio buttons for each row.
Here is the HTML:
<form id="createEdges" method="POST>
<fieldset>
<legend class="title">Modify the graph!</legend>
<table id="createEdgesTable">
</table>
<input type="button" class="btn btn-default" id="backToThirdForm" onclick="goBackToForm3()" value="Back"/>
</fieldset>
And Here is the Javascript:
newNodes = [];
newNodes.push(0);
newNodes.push(1);
//get HTML Table to add rows in
var edgeTable = document.getElementById("createEdgesTable");
//Create a table row for each node
for (var i in newNodes) {
var row = edgeTable.insertRow();
row.id = "node" + i;
//Show name of the node
var td = document.createElement('td');
var text = document.createTextNode(newNodes[i]);
td.appendChild(text);
row.appendChild(td);
//Choice for showing node
var td2 = document.createElement('td');
var radioButton1 = document.createElement('input');
radioButton1.type = "radio";
radioButton1.name = i;
radioButton1.value = "showNode";
td2.appendChild(radioButton1);
row.appendChild(td2);
//Choice for creating edge
var td3 = document.createElement('td');
var radioButton2 = document.createElement('input');
radioButton2.type = "radio";
radioButton2.name = i;
radioButton2.value = "createEdge";
td3.appendChild(radioButton2);
row.appendChild(td3);
//Choice for deleting node
var td4 = document.createElement('td');
var radioButton3 = document.createElement('input');
radioButton3.type = "radio";
radioButton3.name = i;
radioButton3.value = "removeNode";
td4.appendChild(radioButton3);
row.appendChild(td4);
var rowID = row.id;
}
$('#node0 input').on('change', function() {
alert($('input[name=0]:checked', '#node0').val());
});
JSFiddle: https://jsfiddle.net/nxexrq9y/
Any example on how to make this work for each row? I'm relatively new to JQuery and have been stuck on this problem for quite some time now. Thank you for your time and help!
Just change your script with following code.
$('tr[id^=node] input').on('change', function() {
alert(this.value);
});
Explanation:
Scripts find any tr whose id starts with node. this covers all your dynamically generated TRs. Further selection narrows down to only input element in each TR, and registers change event for that element. On that change event your have already got that element so you can easily access its value there.
Here is Js Fiddle Link
Further if you want to know clicked radio falls in which node, you can check out this js fiddle.
$('tr[id^=node] input').on('change', function() {
var row = $(this).parents('tr:first').get(0);
alert('Node: '+ row.id+ ' value:' + this.value);
});
I'm trying to get input from a form and putting it into an array and then putting that array into a new row to a table using DOM manipulation. I have this so far and while it is receiving the value I put in, the value is not displayed in the table but a blank row is inserted. Please help!
(function(){
var theValue;
var formControls = document.getElementById('theForm');
var table = document.querySelector('info');
var handler = function (){
var tbody = document.getElementsByTagName('tbody').item(0);
for (var i = 0; i < 3; i++) {
var tr = 'tr' + [i],
tr = document.createElement('tr');
var displayValue = 'td' + [i],
displayValue = document.createElement('td');
var enteredValue = this['present-value'].value;
theValue = document.createTextNode(enteredValue);
tr.appendChild(displayValue);
tbody.appendChild(tr);
return false;
}
} // end handler
formControls.onsubmit = handler;
})();
HTML
<div id="container">
<div id="controls">
<h2>Controls</h2>
<form id="theForm">
<fieldset>
<label for="present-value">Enter Value</label>
<input id="present-value" name="present-value" type="text">
<button type="submit">Add</button>
</fieldset>
</form>
</div>
<div id="display">
<h2>Values</h2>
<table class="info">
<thead>
<tr>
<th>Value</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
You might look at JQuery's .serializeArray() method:
http://api.jquery.com/serializeArray/
Just some comments:
> var table = document.querySelector('info');
That attempts to get an element with a tag name of "info". There is no such element in HTML.
> var tr = 'tr' + [i],
> tr = document.createElement('tr');
That will overwrite the previous value of tr
> var displayValue = 'td' + [i],
> displayValue = document.createElement('td');
and that will overwrite the previous value of td.
> var enteredValue = this['present-value'].value;
I presume that this is a reference to the form. Does it have a "present-value* attribute or property? This line tries to get the present-value property of the form, then read it's value property. Likely it just throws an error or returns undefined.
Can you post some minimal HTML to go with the code? As far as I can see, the above will not do anything useful.
I have a fairly simple problem (I think) that involves updating a number using jQuery. I have a DIV that holds a price for an item. Users can select a checkbox to add on to the total price. What I need is when someone clicks on a checkbox, it will add the correct amount to the DIV. When a user un-checks a checkbox, the value is subtracted. Here is my code so far:
<div class="cell">
<div class="check">
<input id="check-0" type="checkbox" />
<label for="check-0">$100</label>
<div class="mask"></div>
</div>
</div>
<div class="price">$347</div>
Any help is greatly appreciated!
Hopefully this is something that you could use or help you:
http://jsfiddle.net/VWRAd/
$(".cell").on("click", "input:checkbox", function () {
var $this = $(this);
var $total = $("#price");
var $target = $("label[for='" + $this.attr("id") + "']");
var item_value = +($target.html().replace("$", "") || 0);
var cur_total = +($total.html().replace("$", "") || 0);
if ($this.prop("checked") === true) {
cur_total += item_value;
} else {
cur_total -= item_value;
}
$total.html("$" + cur_total);
});
Although notice that I changed the element with the class of "price" to have an id of "price". It just makes sense, unless you expect to have several "price" elements.
And here is another possible way of doing it...not sure which is better:
http://jsfiddle.net/VWRAd/1/
$(".cell").on("click", "input:checkbox", function () {
var $items = $(".cell").find("input:checkbox:checked");
var $total = $("#price");
var cur_total = 0;
$items.each(function () {
var $this = $(this);
var $target = $("label[for='" + $this.attr("id") + "']");
var item_value = +($target.html().replace("$", "") || 0);
cur_total += item_value;
});
$total.html("$" + cur_total);
});
Some things to consider - it makes sense to separate the "$" from the actual value of the item when displaying it...I'm sure you aren't storing the value with "$", so you might want a structure similar to <label for="whatever">$<span class="the-value">100</span></label>. It would change your jQuery selector logic a little bit, but it would prevent the need for using .replace so often. Also, as someone else already pointed out, it would definitely be easier to store the item's price in the checkbox's value attribute and retrieve it that way (instead of finding the corresponding <label>'s content.
var changePrice = function changePrice(amt, state){
var curPrice = $('.price').text();
curPrice = curPrice.substring(1, curPrice.length);
if(state==true){
curPrice = parseInt(curPrice) + parseInt(amt);
}else{
curPrice = parseInt(curPrice) - parseInt(amt);
}
curPrice = '$' + curPrice;
$('.price').text(curPrice);
}
$(function(){
$('#check-0').on('change', function(){
var itemPrice = $('label[for="check-0"]').text();
itemPrice = itemPrice.substring(1, itemPrice.length);
changePrice(itemPrice, $('#check-0').is(':checked'));
});
});
Demo: http://jsfiddle.net/pratik136/r2Snu/
Even though these may not be form controls intended to hit the server, i would still put the value attribute for each of the inputs.
So for the 'check-0' input, i'd put in a value attribute of 100 (to represent the $100).
Then, a bit of javascript logic should make it easy to update the price value.
So something like this should do it (http://jsbin.com/orodow/1/edit):
<div class="cell">
<div class="check">
<input id="check-0" type="checkbox" value="100" />
<label for="check-0">$100</label>
<div class="mask"></div>
</div>
</div>
<div class="cell">
<div class="check">
<input id="check-1" type="checkbox" value="50" />
<label for="check-1">$50</label>
<div class="mask"></div>
</div>
</div>
<div class="cell">
<div class="check">
<input id="check-2" type="checkbox" value="20" />
<label for="check-2">$20</label>
<div class="mask"></div>
</div>
</div>
<div class="price"></div>
<script>
$(function(){
var inputs = $('.check input:checkbox');
function updatePrice(){
var value = 0;
inputs.filter(':checked').each(function(){
value += parseInt($(this).val(), 10);
});
$('.price').html('$' + value);
}
inputs.change(updatePrice);
});
</script>