When I click the button jQuery append new input inside the div like below:
$('#addIndirectCityBtn').click(function () {
var inputs = $("#additionalCityInputs input").length
if (inputs <= 3) {
$('#additionalCityInputs').append('<input type="text" placeholder="Miasto" class="form-control" style="margin-bottom: 5px;" />')
}
})
How I can add uniqe ID to each new input?
Fore example id="new1" for the second one id="new2" and so on.
Any ideas?
$('#addIndirectCityBtn').click(function () {
var inputs = $("#additionalCityInputs input").length
if (inputs <= 3) {
var newId = 'newId'+(inputs + 1);
$('#additionalCityInputs').append('<input id="'+newId+'" type="text" placeholder="Miasto" class="form-control" style="margin-bottom: 5px;" />')
}
})
Try:
var counter = 0;
$('#addIndirectCityBtn').click(function () {
var inputs = $("#additionalCityInputs input").length
if (inputs <= 3) {
$('#additionalCityInputs').append('<input id="new' + ++counter + '" type="text" placeholder="Miasto" class="form-control" style="margin-bottom: 5px;" />')
}
})
use an IFFE
(function(){
var a = 0;
$('#addIndirectCityBtn').click(function () {
var inputs = $("#additionalCityInputs input").length
if (inputs <= 3) {
$('#additionalCityInputs').append('<input id="new'+ ++a + '" type="text" placeholder="Miasto" class="form-control" style="margin-bottom: 5px;" />')
}
})
}());
Use some counter variable to achieve this.
var i=0;
$('#addIndirectCityBtn').click(function () {
var inputs = $("#additionalCityInputs input").length;
i++;
if (inputs <= 3) {
$('#additionalCityInputs').append("<input id='new"+i+"' type='text' placeholder='Miasto' class='form-control' style='margin-bottom: 5px;' />");
}
});
Related
If I have the following HTML on a page:
<input type="hidden" name=item[0][id]>
<input type="text" name=item[0][title]>
<input type="text" name=item[0][description]>
<input type="hidden" name=item[1][id]>
<input type="text" name=item[1][title]>
<input type="text" name=item[1][description]>
<input type="hidden" name=item[2][id]>
<input type="text" name=item[2][title]>
<input type="text" name=item[2][description]>
I would like to select the items using JavaScript (or JQuery) in such a way that I can loop over the items using the outer array.
Currently I have the following JQuery/JavaScript to handle the items:
var items = ($('[name*="item["]'));
var i = 0;
while (i < items.length) {
if (items[i++].value === '') {
// No ID set.
}
else if (items[i++].value === '') {
// No title set.
}
else if (items[i++].value === '') {
// No description set.
}
}
Is there a way to select the elements so that I can loop over them using notation more like the following (Where items.length is 3)?
for (var i = 0; i < items.length; i++) {
if (items[i][0].value === '') {
// No ID set.
}
else if (items[i][1].value === '') {
// No title set.
}
else if (items[i][2].value === '') {
// No description set.
}
}
Or even more like this?
for (var i = 0; i < items.length; i++) {
if (items[i].id.value === '') {
// No ID set.
}
else if (items[i].title.value === '') {
// No title set.
}
else if (items[i].description.value === '') {
// No description set.
}
}
Or would this require more manipulation and processing to go from selecting from the DOM to creating the data structure to loop over?
I think this is exactly what you are looking for (which is not really related to selectors):
function serialize () {
var serialized = {};
$("[name]").each(function () {
var name = $(this).attr('name');
var value = $(this).val();
var nameBits = name.split('[');
var previousRef = serialized;
for(var i = 0, l = nameBits.length; i < l; i++) {
var nameBit = nameBits[i].replace(']', '');
if(!previousRef[nameBit]) {
previousRef[nameBit] = {};
}
if(i != nameBits.length - 1) {
previousRef = previousRef[nameBit];
} else if(i == nameBits.length - 1) {
previousRef[nameBit] = value;
}
}
});
return serialized;
}
console.log(serialize());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name=item[0][id]>
<input type="text" name=item[0][title]>
<input type="text" name=item[0][description]>
<input type="hidden" name=item[1][id]>
<input type="text" name=item[1][title]>
<input type="text" name=item[1][description]>
<input type="hidden" name=item[2][id]>
<input type="text" name=item[2][title]>
<input type="text" name=item[2][description]>
See the related JSFiddle sample.
Here's a way to add a custom function into JQuery to get the data structure you're looking for.
$.fn.getMultiArray = function() {
var $items = [];
var index = 0;
$(this).each(function() {
var $this = $(this);
if ($this.attr('name').indexOf('item[' + index + ']') !== 0)
index++;
if (!$items[index])
$items[index] = {};
var key = $this.attr('name').replace('item[' + index + '][', '').replace(']', '');
$items[index][key] = $this;
});
return $items;
};
var $items = $('input[name^="item["]').getMultiArray();
This allows you to have the references in your "ideal" example.
var $items = $('input[name^="item["]').getMultiArray();
$items[0].id;
JS Fiddle: https://jsfiddle.net/apphffus/
How to check value in input using getElementsByClassName , Like this ?
When i load page, I want to alert
HAVE VALUE 3 INPUT
NOT HAVE VALUE 2 INPUT
How can i do that ?
................................................................................................................................................
http://jsfiddle.net/3AaAx/37/
<input type="text" class="xxx" value="111"/>
<input type="text" class="xxx" value=""/>
<input type="text" class="xxx" value="222"/>
<input type="text" class="xxx" value=""/>
<input type="text" class="xxx" value="333"/>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
// this function for use getElementsByClassName on IE 7 and 8 //
if (!document.getElementsByClassName) {
document.getElementsByClassName = function(search) {
var d = document, elements, pattern, i, results = [];
if (d.querySelectorAll) { // IE8
return d.querySelectorAll("." + search);
}
if (d.evaluate) { // IE6, IE7
pattern = ".//*[contains(concat(' ', #class, ' '), ' " + search + " ')]";
elements = d.evaluate(pattern, d, null, 0, null);
while ((i = elements.iterateNext())) {
results.push(i);
}
} else {
elements = d.getElementsByTagName("*");
pattern = new RegExp("(^|\\s)" + search + "(\\s|$)");
for (i = 0; i < elements.length; i++) {
if ( pattern.test(elements[i].className) ) {
results.push(elements[i]);
}
}
}
return results;
}
}
var xxx_var = document.getElementsByClassName('xxx');
alert(xxx_var.length);
});
</script>
Add below code after var xxx_var = document.getElementsByClassName('xxx');
var inputCount=0,nonInputCount=0;
for(var i=0;i<xxx_var.length;i++){
if(xxx_var[i].value != ""){
inputCount++;
}else{
nonInputCount++;
}
}
alert("Input Count " + inputCount + " , and non input count " +nonInputCount );
If you use jquery it will be very easier code.
Let me know if you didn't understand.
Thanks
Raviranjan
I want to dynamically add and remove input files, my code works great on all browsers without Internet Explorer. Can anyone help me to resolve my problem?
Here is the Javascript:
<script>
var counter = 1;
var min = 1;
var max = 20;
function addInput(divName) {
if (counter == max) {
alert("Max limit!");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = '<input type="file" name="file[]" id="file"><br>';
document.getElementById(divName).appendChild(newdiv);
document.getElementById("qty").value++;
counter++;
}
}
function remInput(divName) {
if (counter == min) {
alert("Min limit!");
}
else {
var element = document.getElementById(divName);
element.lastChild.remove();
document.getElementById("qty").value--;
counter--;
}
}
</script>
And here is the HTML code:
<input type="button" value="-" onClick="remInput('plus');">
<input type="text" name="qty" id='qty' size='2' style="text-align: center" disabled value="1">
<input type="button" value="+" onClick="addInput('plus');">
<div id="plus">
<input type="file" name="file[]" id="file"><br>
</div>
Thank you.
Its seems that remove() is not supported in IE, do add condition in your code, if particular function is supported in your browser(in this case remove() function)
Please refer below working add.
<script>
var counter = 1;
var min = 1;
var max = 20;
function addInput(divName) {
if (counter == max) {
alert("Max limit!");
}
else {
var newdiv = document.createElement('div');
var inputid="file"+counter;
newdiv.innerHTML = '<input type="file" name="file[]" id='+inputid+'><br>';
document.getElementById(divName).appendChild(newdiv);
document.getElementById("qty").value++;
counter++;
}
}
function remInput(divName) {
if (counter == min) {
alert("Min limit!");
}
else {
var element = document.getElementById(divName);
if(element.lastChild.remove!= undefined)
element.lastChild.remove();
else
element.lastChild.parentNode.removeChild(element.lastChild);
document.getElementById("qty").value--;
counter--;
}
}
</script>
http://jsfiddle.net/R89fn/9/
If any of the text input/Box added are empty then the page must not submit.when I try to retrieve values from the text inputs using their id`s nothing gets retrieved is it possible to retrieve values from elements added dynamically?
$("#submit").click(function (event) {
var string = "tb";
var i;
for (i = 1; i <= count; i++) {
if (document.getElementById(string+1).value=="") {
event.preventDefault();
break;
}
}
});
The above code is what I am using to get the value from the text fields using there id
I took a look on the code in the JSFiddle. It appears that the input textboxes are not given the intended IDs; the IDs are given to the container div.
The code for the add button should use this,
var inputBox = $('<input type="text" id="td1">') //add also the needed attributes
$(containerDiv).append(inputBox);
Check out this solution on fiddle: http://jsfiddle.net/R89fn/15/
var count = 0;
$(document).ready(function () {
$("#b1").click(function () {
if (count == 5) {
alert("Maximum Number of Input Boxes Added");
} else {
++count;
var tb = "tb" + count;
$('#form').append("<div class=\"newTextBox\" id=" + tb + ">" + 'InputField : <input type="text" name="box[]"></div>');
}
});
$("#b2").click(function () {
if (count == 0) {
alert("No More TextBoxes to Remove");
} else {
$("#tb" + count).remove();
--count;
}
});
$("#submit").click(function (event) {
var inputBoxes = $('#form').find('input[type="text"]');;
if (inputBoxes.length < 1) {
alert('No text inputs to submit');
return false;
} else {
inputBoxes.each(function(i, v) {
if ($(this).val() == "") {
alert('Input number ' + (i + 1) + ' is empty');
$(this).css('border-color', 'red');
}
});
alert('continue here');
return false;
}
});
});
<form name="form" id="form" action="htmlpage.html" method="POST">
<input type="button" id="b1" name="b1" value="Add TextBox" />
<input type="button" id="b2" name="b2" value="Remove TextBox" />
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script>
var count = 0;
$(document).ready(function() {
$("#b1").click(function() {
if (count == 5) {
alert("Maximum Number of Input Boxes Added");
} else {
++count;
var tb = "tb" + count;
$(this).before("<div class=\"newTextBox\" id= "+ tb +" >" + 'InputField : <input type="text" name="box[]"></div>');
}
});
$("#b2").click(function() {
if (count == 0) {
alert("No More TextBoxes to Remove");
} else {
$("#tb" + count).remove();
--count;
}
});
$("#submit").click(function(event) {
var string = "#texttb";
var i;
for (i = 1; i <= count; i++) {
if ($('input[type = text]').val() == "") {
event.preventDefault();
break;
}
}
});
});
</script>
<style>
.newTextBox
{
margin: 5px;z
}
</style>
Reason:
you had given id to the div element. so its not get retrive. i had updated the answer with the usage of jquery functions and changed your code for this requirement.
If I understand correctly, your only issue atm is to make sure that the form is not sent if one of the inputs are empty? Seems the solution to your problem is simpler. Simply add required at the end of any input and HTML5 will ensure that the form is not sent if empty. For example:
<input type="text" required />
I'm looking for jQuery code which will list all classess from inputs and display how many times every class (in this case class=value) is selected.
html schema:
<input type="checkbox" name="t1" class="a1" value="a1">
<input type="checkbox" name="t1" class="a2" value="a2">
<input type="checkbox" name="t1" class="a3" value="a3">
<input type="checkbox" name="t2" class="a1" value="a1">
<input type="checkbox" name="t2" class="a2" value="a2">
<input type="checkbox" name="t2" class="a3" value="a3">
...
<input type="checkbox" name="t9" class="a99" value="a99">
example of expected result:
a1 - 2
a2 - 0
a3 - 0
a99 - 0
Try
var map = {};
$('input[type=checkbox]').each(function () {
if (this.checked) {
map[this.className] = (map[this.className] || 0) + 1;
} else {
map[this.className] = map[this.className] || 0;
}
});
console.log(map)
Demo: Fiddle
You could try something like this:
var checked = new Array();
$("input[type=checkbox]").each( function() {
var cl = $(this).attr('class');
if (typeof(checked[cl]) == "undefined") checked[cl] = 0;
if ($(this).is(':checked')) checked[cl]++;
});
After this, you will have variable checked containing all checkbox classes, with number of checked boxes for each class.
Let me know if this works for you.
Fiddle: http://jsfiddle.net/smBSw/1/
var resultList = {}
$('input:checkbox').each(function () {
var result = resultList[this.className] || 0;
if (this.checked) {
result++;
}
resultList[this.className] = result;
});
console.log(resultList)
console.log(JSON.stringify(resultList));
You can use like :
var className = [];
$("#btn").click(function () {
$("#result").html("");
$("input[class^=a]").each(function () {
className.push($(this).attr("class"));
});
className = jQuery.unique(className);
for (i = 0; i < className.length; i++) {
var count = 0;
$("." + className[i]).each(function () {
if (this.checked) {
count++;
}
});
$("#result").append(
"<br/><span> " +
"className: " + className[i] + ", " +
"count :" + count +
"</span>"
);
}
});
demo fiddle
Basically you will need to iterate through these inputs.. but you will need a place to save the counts
$(".checkboxes").on("change", "input", function() {
var results = {"a1": 0, "a2": 0, "a3": 0};
$(".checkboxes input").each(function(i, checkbox) {
if (!$(checkbox).prop("checked")) {
return;
}
results[$(checkbox).val()] = results[$(checkbox).val()] + 1;
});
var resultsToAppend = '';
$.each(results, function(key, value) {
resultsToAppend += '<li>' + key + ' : ' + value + '</li>';
});
$(".results").html(resultsToAppend);
});
Here's a fiddle