I am trying to clone and insert items in order in JS, I can clone and add elements but the order seems to be incorrect, I am trying to assign a value to the radio buttons so I can tie the radio buttons to the text fields as seen below:
<div id='1'>
<div class="template">
<div>
<label class="right inline">Response:</label>
</div>
<div>
<input type="text" name="responseText[]" value="" maxlength="400" />
</div>
<div>
<input type="checkbox" name="responsCheck[]" value="0" />
</div>
</div>
<div>
<input type="button" name="addNewRow" value="Add Row" />
</div>
</div>
JS:
var $counter = 0;
var $template = $('.template');
$('input[type=button]').click(function() {
var $elem = $template.clone();
$elem.find("input:text").val("");
$copy.find("input:radio").val($counter);
$elem.insertAfter($template);
});
If I add three rows for example, the Values of the checkbuttons are in the following order:
0
2
1
I need the Values to be in the following order:
0
1
2
anybody got any ideas? I think it must be the way I am inserting the clone? When I am using radio buttons this line seems to work:
$elem.insertAfter($('#1 .clone').last());
but when using checkboxes it doesn't seem to work any ideas?
To me problem looks like that on adding second entry $template still points to the first entry.
I would try by moving $template initialization inside click handler and changing it like below.
var $counter = 0;
$('input[type=button]').click(function() {
var $template = $('.template:last');
});
This way $template should point to the last template inserted and it should work as expected.
Maybe you need to use:
$("#1").append($elem);
instead
$elem.insertAfter($template);
Or select the last every time.
var $template = $('.template').last();
Put them into a js array and sort them by val:
function SortByValue(elem1, elem2){
var e1 = Number($(elem1).val());
var e2 = Number($(elem2).val());
return ((e1 < e2) ? -1 : ((e1 > e2) ? 1 : 0));
}
var sortedValues = $.makeArray($(jQSelector)).sort(SortByValue);
Here is a fiddle
Related
I am trying to create button labels based off of user input by inserting a span with the label text via js. The id's of all my buttons are numbers in a sting format so id="0", id="1", etc.
The following function will only label the first button with id="0".
gearInputs = document.getElementsByClassName('Box');
for (i=0; i<gearInputs.length; i++) {
var gearName = gearInputs[i].value,
gearButton = document.getElementById(i);
if(gearName && gearName != ''){
gearButton.innerHTML = '<span class="resultsButtons">' + gearName + '</span>';
}
}
My buttons:
<button id="0" class="buttonshowHide" onclick="showHide(this.id)"></button>
My input box:
<input placeholder="Enter Camera/Lens Model" class="Box" type="text" id="gearInput1"/>
I have also tried i.toString(); with no luck. If I enter 0 as the id in document.getElementById it will label the first button but if i put 1, 2 etc it fails whether I enter it as 1, "1", or i.toString(); where i is 1.
I am sure this is simple and I am just overlooking something.
I'm not sure if I'm reading the question wrong, excuse me if that is the case. It sounds to me like you have html elements like this:
<input class="gearInput" id ="gearInput0" value="test1">
<input class="gearInput" id ="gearInput1" value="test2">
<input class="gearInput" id ="gearInput2" value="test3">
<button class="someClass" id="0"> </button>
<button class="someClass" id="1"> </button>
<button class="someClass" id="2"> </button>
And you are wanting the output of this function to be:
<button class="someClass" id="0"> test1 </button>
<button class="someClass" id="1"> test2 </button>
<button class="someClass" id="2"> test3 </button>
And so on. The array spanHtml is useless, as it always only contains one item, since you clear it in each block of the loop. The gearNames array is also not needed unless you are using it for some other function.
I would do something like this:
gearInputs = document.getElementsByClassName('gearInput');
for (i=0; i < gearInputs.length; i++){
var gearName = gearInputs[i].value,
gearButton = document.getElementById(i);
if(gearName && gearName != ''){
gearButton.innerHTML = '<span class="resultsButtons">' + gearName + '</span>';
}
}
The if block only being to ensure they put a value into the input remove that if you don't care about that.
Heres what that would look like. Hope this helps.
https://jsfiddle.net/edh4131/70v551qp/
edit: spacing
I figured this out. I had to change the button id's from id="0", id="1", etc to id="btn0", id="btn1" etc. After I did that edh4131's solution worked fine.
I want to be able to display the same piece of html code 10 times under the div called: <div id="add_remove_product_name"> By clicking on the button called: <button id="add_another_product_name">. I think I need some kind of a for loop for the job but are not sure. Any suggestion will be helpful, thanks.
My HTML code:
<div id="product_name">
<input id="skriv_produktnavn" placeholder="Skriv Produktnavn her" required></label>
<button id="add_another_product_name">Tilføj endnu et produktnavn</button>
<div id="add_remove_product_name">
<input id="added_product_name" placeholder="Skriv Produktnavn her" required></label>
<button id="remove_product_name">X</button>
</div>
Use a for loop to concatenate 10 copies of the HTML code. Then use .after() to put this after the DIV.
$("#add_another_product_name").click(function() {
var html = '';
for (var i = 0; i < 10; i++) {
html += 'html code that you want to repeat';
}
$("#add_remove_product_name").after(html);
}
You can use jQuery clone() however when cloning an element all the attributes will be the same. Fo example they will all have the same id attribute which will cause problems and it is not valid html
So in order to do the clone correctly you have fix the cloned element
DEMO: http://jsfiddle.net/rpyt445e/
var $tpl = $('#product_name').clone();
var num = 0
$('#clone').click(function () {
num++;
var $cloned = $tpl.clone();
$cloned.attr('id', $tpl.attr('id') + '_' + num);
$(':not([id=""])', $cloned).each(function(){
$(this).attr('id', $(this).attr('id') + '_'+num);
});
$cloned.appendTo('#wrapper');
});
HTML:
<div id="wrapper">
<div id="product_name">
<input id="skriv_produktnavn" placeholder="Skriv Produktnavn her" required />
<button id="add_another_product_name">Tilføj endnu et produktnavn</button>
<div id="add_remove_product_name">
<input id="added_product_name" placeholder="Skriv Produktnavn her" required />
<button id="remove_product_name">X</button>
</div>
</div>
</div>
<button id="clone">Clone</button>
A technique for adding the additional elements without having to create ugly strings of html in the JavaScript is to start with one hidden set of the elements in the html. At page load time, you remove that set, but keep a reference to it. Then when you want to add a set to the page, you clone the set you removed. All of this is easier if you add a container div around the additional inputs.
You also need to make sure id attribute values are unique. In the case of the remove buttons, you can replace the id with a class. As for the input id values, if you really need them, you can add an index value to them.
Since the remove buttons are dynamically added, I suggest using event delegation when binding the click-handler.
HTML:
<div id="product_name">
<input id="skriv_produktnavn" placeholder="Skriv Produktnavn her" required="required"/>
<button id="add_another_product_name">Tilføj endnu et produktnavn</button>
<div id="additional_product_names">
<div class="add_remove_product_name" style="display: none;">
<input id="added_product_name" placeholder="Skriv Produktnavn her" required="required"/>
<button class="remove_product_name">X</button>
</div>
</div>
</div>
JavaScript:
$(function() {
var MAX = 10;
var $addBtn = $('#add_another_product_name'),
$additionalContainer = $('#additional_product_names');
$TEMPLATE = $additionalContainer.children(':first').remove();
function update() {
var $additonalDivs = $additionalContainer.children();
// Enable/disable the add button.
$addBtn.prop('disabled', $additonalDivs.length >= MAX);
// Re-index the "id" attributes.
$additonalDivs.find('input').attr('id', function(i) {
return 'added_product_name[' + i + ']';
});
}
$addBtn.click(function() {
$TEMPLATE.clone().appendTo($additionalContainer).show();
update();
});
$('#product_name').on('click', '.remove_product_name', function() {
$(this).closest('.add_remove_product_name').remove();
update();
});
});
jsfiddle
I'm trying to add the rows dynamically plus auto-increment of a counter.I want to start with 1 then 2 then 3 and so on . I have added my code on plunker ,in which every time the max value is getting in first column like 4 then 1,1,2,3.Where am i going wrong ?i Want it to be 1,2,3,4.
Here is the plunker link http://plnkr.co/edit/GuDbJ3SHOPvWkHfNfd8E?p=preview
var _counter = 0;
function Add() {
_counter++;
var oClone = document.getElementById("template").cloneNode(true);
oClone.id += (_counter + "");
document.getElementById("placeholder1").appendChild(oClone);
document.getElementById("myVal").value=_counter;
}
<div id="placeholder1">
<div id="template">
<div>
Value:<input type="text" id="myVal" placeholder="1">
Quantity:<input type="text" placeholder="Qty">
<input type="button" onClick="Add()" value="Click! ">
</div>
</div>
I think it is because you have multiple divs with the id="myVal". The id attribute should be unique on the page. If not, your page will still load, but you may have unexpected behavior.
You are changing the id of the template div, but not the myVal div.
I assume you are looking for something like this:
var _counter = 0;
function Add() {
_counter++;
var oClone = document.getElementById("template").cloneNode(true);
oClone.id += (_counter + "");
document.getElementById("placeholder1").appendChild(oClone);
oClone.getElementsByClassName("myVal")[0].value = _counter;
}
<div id="placeholder1">
<div id="template">
<div>
Value:
<input type="text" class="myVal" placeholder="1">Quantity:
<input type="text" placeholder="Qty">
<input type="button" onClick="Add()" value="Click! ">
</div>
</div>
</div>
In your original you are cloning your template with the same id for the input. So when you do document.getElementById("myVal").value=_counter;, you only get the first input. I changed it to use class instead and get the input with the appropriate class that is a child of the cloned node.
Hi all I have a form in which I dynamically add in a new row consisting of a text box and check button on button press. However I need some sort of way to know which checkbuttons were pressed in the post data and therefore need a value field consisting of an ID on each of the the check buttons, code is seen below:
<div id='1'>
<div class="template">
<div>
<label class="right inline">Response:</label>
</div>
<div>
<input type="text" name="responseText[]" value="" maxlength="400" />
</div>
<div>
<input type="radio" name="responseRadio[]" value="" />
</div>
</div>
<div>
<input type="button" name="addNewRow" value="Add Row" />
</div>
</div>
JS to add new row:
var $template = $('.template');
$('input[type=button]').click(function() {
$template.clone().insertAfter($template);
});
can anyone suggest a good way to help me know in the post data which text field, links to which check button, and to know if it was pressed?
at the moment if you were to add 3 rows and check row 3 I have no way of identifying that row three was the button pressed - This is my issue
after you cloned it, change the name so you know about this input
also it's good to have a counter for naming:
like : 'somename[myInput' + counter + ']'
update:
var counter = 0;
var $template = $('.template');
$('input[type=button]').click(function() {
counter++;
$template.clone().attr('name' , 'somename[myInput' + counter + ']').insertAfter($template);
});
now you have array named:somename which you can have a loop over its content on your form handler.
Please forgive me if I repeat the question.
I have HTML that all elements inside a div tag has different id, suppose I have already get the reference to the div, is there any simple way to get the element by its id without iterate all elements with that div?
here is my sample html:
<div id="div1" >
<input type="text" id="edit1" />
<input type="text" id="edit2" />
</div>
<div id="div2" >
<input type="text" id="edit1" />
<input type="text" id="edit2" />
</div>
You may try something like this.
Sample Markup.
<div id="div1" >
<input type="text" id="edit1" />
<input type="text" id="edit2" />
</div>
<div id="div2" >
<input type="text" id="edit3" />
<input type="text" id="edit4" />
</div>
JavaScript
function GetElementInsideContainer(containerID, childID) {
var elm = {};
var elms = document.getElementById(containerID).getElementsByTagName("*");
for (var i = 0; i < elms.length; i++) {
if (elms[i].id === childID) {
elm = elms[i];
break;
}
}
return elm;
}
Demo: http://jsfiddle.net/naveen/H8j2A/
A better method as suggested by nnnnnn
function GetElementInsideContainer(containerID, childID) {
var elm = document.getElementById(childID);
var parent = elm ? elm.parentNode : {};
return (parent.id && parent.id === containerID) ? elm : {};
}
Demo: http://jsfiddle.net/naveen/4JMgF/
Call it like
var e = GetElementInsideContainer("div1", "edit1");
var x = document.getElementById("parent").querySelector("#child");
// don't forget a #
or
var x = document.querySelector("#parent").querySelector("#child");
or
var x = document.querySelector("#parent #child");
or
var x = document.querySelector("#parent");
var y = x.querySelector("#child");
eg.
var x = document.querySelector("#div1").querySelector("#edit2");
You don't want to do this. It is invalid HTML to have more than one element with the same id. Browsers won't treat that well, and you will have undefined behavior, meaning you have no idea what the browser will give you when you select an element by that id, it could be unpredictable.
You should be using a class, or just iterating through the inputs and keeping track of an index.
Try something like this:
var div2 = document.getElementById('div2');
for(i = j = 0; i < div2.childNodes.length; i++)
if(div2.childNodes[i].nodeName == 'INPUT'){
j++;
var input = div2.childNodes[i];
alert('This is edit'+j+': '+input);
}
JSFiddle
A given ID can be only used once in a page. It's invalid HTML to have multiple objects with the same ID, even if they are in different parts of the page.
You could change your HTML to this:
<div id="div1" >
<input type="text" class="edit1" />
<input type="text" class="edit2" />
</div>
<div id="div2" >
<input type="text" class="edit1" />
<input type="text" class="edit2" />
</div>
Then, you could get the first item in div1 with a CSS selector like this:
#div1 .edit1
On in jQuery:
$("#div1 .edit1")
Or, if you want to iterate the items in one of your divs, you can do it like this:
$("#div1 input").each(function(index) {
// do something with one of the input objects
});
If I couldn't use a framework like jQuery or YUI, I'd go get Sizzle and include that for it's selector logic (it's the same selector engine as is inside of jQuery) because DOM manipulation is massively easier with a good selector library.
If I couldn't use even Sizzle (which would be a massive drop in developer productivity), you could use plain DOM functions to traverse the children of a given element.
You would use DOM functions like childNodes or firstChild and nextSibling and you'd have to check the nodeType to make sure you only got the kind of elements you wanted. I never write code that way because it's so much less productive than using a selector library.
A simple way to do what OP desires in core JS.
document.getElementById(parent.id).children[child.id];
In HTML ids should be unique. I suggest you change your code to something like this:
<div id="div1" >
<input type="text" name="edit1" id="edit1" />
<input type="text" name="edit2" id="edit2" />
</div>
<div id="div2" >
<input type="text" name="edit1" id="edit3" />
<input type="text" name="edit2" id="edit4" />
</div>
Sample Html code
<div id="temp">
F1 <input type="text" value="111"/><br/>
F2 <input type="text" value="222"/><br/>
F3 <input type="text" value="333"/><br/>
Type <select>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<input type="button" value="Go" onclick="getVal()">
</div>
Javascript
function getVal()
{
var test = document.getElementById("temp").getElementsByTagName("input");
alert("Number of Input Elements "+test.length);
for(var i=0;i<test.length;i++)
{
if(test[i].type=="text")
{
alert(test[i].value);
}
}
test = document.getElementById("temp").getElementsByTagName("select");
alert("Select box "+test[0].options[test[0].selectedIndex].text);
}
By providing different tag names we can get all the values from the div.
Unfortunately this is invalid HTML. An ID has to be unique in the whole HTML file.
When you use Javascript's document.getElementById() it depends on the browser, which element it will return, mostly it's the first with a given ID.
You will have no other chance as to re-assign your IDs, or alternatively using the class attribute.