Count Dynamically created html elements with jquery - javascript

I am counting the number of inputs on the current document that have value. It works fine, except for when I have dynamically added more inputs. I can't get there values.
For example I may have
<input id="participant-1"/>
<input id="participant-2"/>
...
Dynamically created after button click
<input id="participant-15" />
I'll get the value of each one in a for loop like
for(var i =1 ; i <25; i++)
{
...$('input#participant-' + i).val();
}
Now when I run a for loop to check the value of each one of these inputs it only gets the values of the inputs that weren't dynamically created. I have looked at the other questions on here and I still can't see how to apply something like .on() to what I am trying to accomplish.
NEW FOLLOW UP QUESTION
ok, now I think this is where I need more clarification concerning how to use the .on.
I have a jsfiddle here: JsFiddle example
where I create new elements and on blur of all text boxes I would like to calculate how many of the elements have value and log it. Now it currently will respond from blur event with elements who were static. It doesn't work for dynamically created elements

Give it a common class:
<input class="textbox" id="participant-1"/>
<input class="textbox" id="participant-2"/>
And get it like:
var values = [];
$('.textbox').each(function(){
values.push($(this).val());
});
console.log(values)
And to answer the edit:
The Syntax should be : $(container_selector).on(event_type, target_selector, callback)
JSFiddle Demo
$('.name').on('blur', 'input', calculate_total);

Could also consider the use of the CSS attribute selector.
http://www.w3.org/TR/CSS2/selector.html#attribute-selectors
$("input[id|=participant]").each(function(){
// something
});

Using a class selector will save time here.
<input id="participant-1" class="participant"/>
<input id="participant-2" class="participant"/>
Then use a simple count call...
var count = $('.participant').length
alert ('You have ' + count + ' Counted Inputs');
//result is 2
Hope you find this useful

Related

How do you put the value of a select-element into a textarea?

I'm trying to add a function where you select a color of a shirt from a select-element and add it to the textarea when you press the button.
Also if anyone can give advice to do the same with a group of radio buttons, that would help a lot.
JavaScript
function addShirt() {
buildStr += document.shirtInfo.color.value;
}
HTML
<form name="shirtInfo">
<h1>Shirts</h1>
<select name="color">
<option>White Shirt</option>
<option>Black Shirt</option>
<option>Grey Shirt</option>
</select>
<input type="button" name="complete" value="Submit" onclick="addShirt()"/>
<textarea name="receipt" rows="10" cols="15"></textarea>
Please use IDs in your HTML. Anyone trying to access your DOM will find it a lot easier to modify if they can just call an ID.
So, all you really want to do is add to the value of the textarea.
// First, define the type of variable that you want (I chose an array)
// You don't have to, but it's easier for me to iterate over
var buildstr = [];
// I'm adding this event listener on the Javascript side
// so it doesn't require you changing the HTML to modify it
document.shirtInfo.complete.addEventListener("click", function(e) {
// Take the value of the dropdown and add it to the end of the array
buildstr.push(document.shirtInfo.color.value);
// Then overwrite the value of the textarea with the array
document.shirtInfo.receipt.value = buildstr;
})
You can use the getElementsByName javascript function to access your textarea in javascript. Once you have access to the DOM element representing your textarea in javascript, you can use the innerHTML property to change its content.
function addShirt() {
document.getElementsByName("receipt")[0].innerHTML += document.shirtInfo.color.value;
}
You should take note that getElementsByName returns an array. That is the reason why you have to take the first element of that array. You could also use getElementById, which returns only one element, after having added a unique id attribute to your textarea.
To make your results clearer, you might want to add a new line after each color you add :
document.getElementsByName("receipt")[0].innerHTML += document.shirtInfo.color.value + "\n";

Using variables in javascript to reference html elements dynamically

I am trying to use jQuery / javascript to remove a class from a named input element if a checkbox is ticked.
I have several checkboxes, each with a accompanying hidden (on page load) text input field.
The checkbox and text input field are named "question_X" and "question_X_description" respectively. (where X is a number 0 to 100, say)
As such I'm trying to define a variable in my code that is defined as "this element's name"+"_description", and then use that to define the suitable element to remove the class from.
Here is what I've tried:
$('input:checkbox').change(function(){
var x = $(this).attr('name').'_description';
if($(this).is(":checked")) {
$('input[name="x"]').removeClass("hidden");
} else {
$('input[name="x"]').addClass("hidden");
}
});
However, nothing happens when the any checkbox is checked. Am I referencing my variable correctly?
Use your console, It will have error messages.
First issue
var x = $(this).attr('name').'_description';
^^^
That is not how you build a string in JavaScript. JavaScript does not use . to join strings. It uses +
var x = $(this).attr('name') + '_description';
Second issue
$('input[name="x"]').
You are not looking for the string you built, you are looking for an element with the name x
Needs to be
$('input[name="' + x + '"]').
$('input[name="x"]').removeClass("hidden");
Will be looking for:
<input name="x" />
Try
$(name="'+x+'").removeClass("hidden");
Use document.getElementById('element_name')
Example of HTML element:
<input type="text" id="element_name">

Why jquery validation is not working on appended elements?

I have a form and I want to add new elements as you can see in this fiddle I used append $('#cvfields').append(campos); to add this elements but the jquery validation plugin started to giving me problems. I found this in some answers related whith this question
$('#titulo_'+campo).rules('add', {'required': true});
$('#tipo_'+campo).rules('add', {'required': true});
But when I added .rules code I received this error
Uncaught TypeError: Cannot read property 'form' of undefined
$.extend.rules
(anonymous function)
x.event.dispatch
v.handle
Hope you can help!
You have some issues with your code:
1) When you use the .rules('add') method on a selector of multiple elements, you must nest it inside a jQuery .each() or it won't be applied to all the matching elements.
$('.newinput').each(function() {
$(this).rules('add', {
'required': true
});
});
However, you can probably skip .rules() entirely. See item #2 below.
2) You can totally forget about item #1 above since you're only trying to make these new fields required. Simply add a required="required" attribute (which I see you've already done) when you create them and you will not need to worry about the .rules('add') method at all. Alternatively, you could use class="required" instead, which is the method I chose for the demo below.
3) This is why nothing was working: Your newly added elements must also contain unique names. It's a requirement of the plugin that all form inputs need a name atribute. It's how the plugin keeps track of the elements, so they all need to be unique. However, as per your code, they do not. Your newly created elements all have the same exact name assigned to them as your existing elements. Fix it by adding a counter and incrementing it to the name each time you append to the form.
$(function () {
validar();
cvFields();
});
function validar() {
$(".validate").validate({
....
});
}
function cvFields() {
var count = 0;
$('#addcvfields').click(function (e) {
e.preventDefault();
count++;
var total = $()
var campos = '' +
....
'<input name="profesorcv_titulo[' + count + ']" type="text" class="form-control required" placeholder="Titulo de Estudio o Experiencia">' +
....
'<select name="profesorcv_tipo[' + count + ']" class="form-control required">' +
....
'<textarea rows="3" name="profesorcv_descripcion[' + count + ']" class="form-control" id="profesorcv_descripcion" placeholder="Describe Brevemente"></textarea>' +
....;
$('#cvfields').append(campos);
});
}
you get these problems because the added form elements where not in the DOM when your form validation plugin get initialized. you have to call your validation plugin again, after you've added new elements to the DOM.
EDIT: I just had a look at your fiddle code. your problem can be solved by first calling cvFields() and then validar();
$(function(){
cvFields();
validar();
});
If you first call validar(), the function will look in the DOM (document) if there are elements with the class ".validate". If there are elements with this class they'll get processed by the function. However all the elements that are added to the DOM after the validar() function won't get processed because they were not present in the DOM when the validar() function was called.
If you want to get the validating work after you added more items to validate you simply have to do validar(); again.

How to get an element by name and set its value

There should be a simple solution for this. I need to get an input element by name and set its value.
The following Javascript does not work:
x = document.getElementsByName($('#questions').val());
x.value=this.value;
Is there a simple solution using JQuery?
Description
You are mixing normal javascript and jQuery.
Use the attribute selector.
Check out my sample and this jsFiddle Demonstration
Sample
Html
<input type="text" name="nameOfTheInputElement"/>
jQuery
$(function() {
$("input[name='nameOfTheInputElement']").val("your value");
});
​
Edit
If you want, for some reason, change a element which name is a value in another element
then do this. jsFiddle Demonstration
Html
<input type="text" id="questions" value="nameOfTheInputElement"/>
<input type="text" name="nameOfTheInputElement"/>
​jQuery
$(function() {
var name = $("#questions").val();
$("input[name='"+name +"']").val("your value");
});​
More Information
jQuery - Attribute Equals Selector [name="value"]
jsFiddle Demonstration (first sample)
jsFiddle Demonstration (second sample)
A simple, pure JavaScript (and therefore faster) solution:
var x = document.getElementsByName(document.getElementById('questions').value)[0].value = this.value;
I know jQuery's tagline is 'Write less, do more', and in many cases it is true... many cases !== always, though ;-)
getElementsByName() returns a node-list, so you need to get the first one getElementsByName(...)[0]
But you are already using jQuery, so use it. Read some tutorials about the jQuery selectors
Try this
var q = $("#question").val();
var x = $("input[name='" + q + "']").val();
on the 2nd line, variable q, the name provided in input with id 'question', will be enclosed with ' and could contain any supported characters, like space, :, -, etc
If you need the value of a component regardless of its tag, you can do this:
var x = $("[name='" + q + "']").val();
Consider that this approach $("[name='" + q + "']") can return more than one element, but .val() will return only the value of the first element.
If I'm understanding your question correctly, you want to get an element by name, and the name of the element you're selecting will be specified by some dropdown or text area.
Here's my take on it:
Html
<input type="text" id="enteredName">
<button id="doTheStuff">Do the work</button>
<input name="one" value="One">
<input name="two" value="Two">
jQuery
$('#doTheStuff').click(function(){
var objectOfInterest = $('[name=\'' + $('#enteredName').val() + '\']');
alert(objectOfInterest.val());
});
Working example
Here's another working example using a dropdown to specify the selection name.
$('#form-id input[name="name-input"]').val('your value');

How to generate Divs containing tables with dynamically addable and removable rows? - JSfiddle Added

In the JSFiddle, I am trying to generate divs dynamically using javascript. Those divs will contain tables where the last two rows can be incremented using the add button.
I have tried the code in the fiddle.
The ins_row() function is used to add rows in the table which are generated within the divs.
The addEvent() function is used to generate divs
When the Add product button is clicked a div containing a table with one row will get generated.
When the add button is clicked the last two rows should keep on getting added as per the clicks. If the remove button straight to the div is clicked the whole table and div should be deleted.
When the remove button straight to the generated rows is clicked, only that row should be deleted and not the whole div.
Problem
The problem here is the divs with table are getting generated but I couldn't figure out how to add the rows in the table.
See it in action here
Expected output
Note: I have just pasted the external JS file into the javascript column of the above fiddle as I don't have the resource link.
Present output
I hope I have presented the question understandable, if anything is not clear, Please let me know
I believe I have properly understood your requirement.
Try out this fiddle http://jsfiddle.net/Kucuk/14/
It uses jquery though - its just a sample sort of thing that you could probably base your own code off. Its all doable in plain old JavaScript, if that's what you prefer. The styling is a bit off, but that you can handle I hope.
Do let me know if this helps you in some manner.
Generally, I use jQuery's appendTo() function alongwith a dummy html structure. I store this in a variable & follow it up with further attribute manipulation.
To get an idea of what I am talking about, just check this fiddle: http://jsfiddle.net/GGS4N/
This is in answer to another question Smooth out this jQuery toggle animation?. Focus on the methodology as listed below:
To create a dummy HTML structure(generic in nature).
On your desired event, triggering of population and manipulation of the dynamic elements into the dom, with giving them an identifiers and manipulating other specific attributes, and as seen in the fiddle, even animating them.
If you prefer raw JS, as seen from your code, you can implement the same functionality in raw JS too! :)
Try this fiddle to see if it works for you.
In this example, when you click on add product, all 4 textboxes are created with an add more rows and remove div buttons.
When you click on add rows, last two textboxes are created with a remove row button.
Whenever the row count of a product is more than 1, the remove div button is hidden and is shown again when the row count is 1.
Is this more like what you expected?
http://jsfiddle.net/7AeDQ/81/
I achieved this by adding styles to widen the table and the cell containing the buttons. I also changed the buttons to input type="button".
Hope this works for you.
EDIT:
I have just noticed that I mixed up your expected output and present output. Working on expected output now.
Another pure js solution
<html>
<body>
<script>
var tblCount = 0
var tblIdStr = "productTbl";
function removeRow(id, rowNumber) {
var el = document.getElementById(id);
el.deleteRow(rowNumber);
}
function addTable() {
++tblCount;
tblId = tblIdStr + tblCount;
var args = "'" + tblId + "'";
var tblHtml = '<tr><td>Product name</td><td>Price</td><td>Competitor</td><td>Price</td></tr><tr><td><input type="text"></td><td><input type="text"><td><input type="text"></td><td><input type="text"></td><td><input type="button" value="Add" onclick="addRow(' + args + ')"></td><td></td></tr>'
var tbl = document.createElement("table");
tbl.setAttribute("id", tblId);
document.getElementById("container").appendChild(tbl)
document.getElementById(tblId).innerHTML = tblHtml;
}
function addRow(id) {
var el = document.getElementById(id)
var rowCount = el.rows.length;
var row = el.insertRow(rowCount);
//console.log(row)
var args = "'" + id + "'" + "," + rowCount;
var tblRowHtml = '<td colspan=2></td><td><input type="text"></td><td><input type="text"></td><td><input type="button" value="remove" onclick="removeRow(' + args + ')"></td>';
//el.rows[rowCount].setAttribute("id", rowId);
el.rows[rowCount].innerHTML = tblRowHtml
}
</script>
<input type="button" value="Add new product table" onclick="addTable()">
<div id="container">
</div>
</body>
</html>

Categories

Resources