Change all id's in HTMLDivElement using jQuery - javascript

I am using jQuery to dynamically append a Django formset.
I am using a link to add another form identical to the one above it. I do this with the following code:
var row = $("."+class_name).first().clone(true);
row.find('input').val('');
$(row).removeAttr('id').hide().insertAfter("."+class_name).last().slideDown(300);
Every label in row[0] (which is a HTMLDivElement) is id_cur-0-... And everytime I use this jQuery function to add a div, I need every id to increment the number after cur. So the first time I click it every item would have id_cur-1... And the next time they would have id_cur-2... And so on.
If I could treat the HTMLDivElement like a string I could use regex to basically find every occurrence of "cur-\d". How would I do this? Or is there a better way (because this kind of seems like a hack).
Here's what my HTML looks like:
<div class="item1">
<label style="display:inline-block;" for="id_cur-0-cur_child_name">
Name:
</label>
<input style="display:inline-block;width:10%" class="textinput textInput form-control" id="id_cur-0-cur_child_name" name="cur-0-cur_child_name" type="text" />
<label style="display:inline-block;" for="id_cur-0-cur_child_sex">
Sex:
</label>
<input style="display:inline-block;width:10%" class="textinput textInput form-control" id="id_cur-0-cur_child_sex" name="cur-0-cur_child_sex" type="text" placeholder="[M / F]" />
<label style="display:inline-block;" for="id_cur-0-cur_child_dob">
DOB:
</label>
<input style="display:inline-block;width:10%" class="textinput textInput form-control" id="id_cur-0-cur_child_dob" name="cur-0-cur_child_dob" type="text" placeholder="e.g. 12/25/2014" />
</div>

Would this do?
var last_id = $("."+class_name).last().attr("id").split("-")[1];
fiddle
UPDATE
Hi there, the ev.preventDefault only serves the purpose of preventing the default behaviour of the anchor. It stops the default action of an element from happening.
I saw your html and here you have a new fiddle
Javascript code (commented):
$("#clone").click(function (ev) {
ev.preventDefault();
var row = $(".item1").last().clone(true);// Last item1
var last_id = $(row).find("input:first").attr("id");// Grab first input id (it contains the important part: the number)
row.find('input').val('');
$.each(row.find('input'), function (index, item) {// Change id of all inputs inside the cloned element.
var id = (+(last_id.split("-")[1])+1), // Grab the number and increase it.
new_id = $(item).attr("id").replace("id_cur-" + last_id.split("-")[1], "id_cur-" + id);// Replace ids with the new number.
$(item).attr("id",new_id);// Asign the new id to the inputs. You'll have to do more or less the same to the labels if you like.
});
$(row).removeAttr('id').hide().insertAfter(".item1:last").slideDown(300);// Insert after the last item1 element. Otherwise it'll insert after all elements with class .item1
});
Hope it helps.
Kind regards.

Instead, you can use id_cur as the class name, and the specific id with the id attribute as such:
var last_row = $("."+class_name+":last");
var new_row = last_row.clone(true);
new_row.attr('id', new_row.attr('id')+1);
new_row.find('input').val('');
new_row.removeAttr('id').hide().insertAfter(last_row)
new_row.slideDown(300);
You simply have to increment the id attribute with the last one + 1.
Just for clarification: You were using first() to select the first matched element and clone it in var row = $("."+class_name).first().clone(true);, but in this case, if we want to increment the id accordingly, we must clone the latest element added.
Hope this helps !
Cheers,

I could use regex to basically find every occurrence of "cur-\d".
Use the JQuery regex selector to find all id or whatever attr.
Select all the label tag element in which the for attribute start with id-cur-
$("label[#for^=id-cur-]")
Select all input tag element with id beginning with id-cur-
$("input[#id^=id-cur-]")
Hope this may help to select the dom element with regex.

Related

How to get value of another input field using javascript

How to find the value of text field using onblur() in next input field.
I tried:
function get_value() {
var inv_nrs;
inv_nrs = document.getElementsByTagName('text1').value;
alert(inv_nrs);
}
text1 is name of input which I am trying to get value.
text2 is name of input where onblur() is triggered.
Two problems:
To get elements by their name attribute, use document.getElementsByName(), not document.getElementsByTagName.
Since these functions return a collection, not a single element, you have to index them to get a specific element.
So the function should be:
function get_value() {
var inv_nrs;
inv_nrs = document.getElementsByName('text1')[0].value;
alert(inv_nrs);
}
Here's a simple snippet which illustrates a way to do this.
(You may wish to use alert in place of console.log)
document.getElementById("text2").onblur = function() {
console.log(document.getElementById("text1").value)
}
<input type="text" id="text1" value="123" />
<input type="text" id="text2" />
Are you looking for an element with id = "text1" or real name = "text1"?
At least if it's their id try getElementById("text1"), that returns one single element. If you talking about the name-attribute, take getElementByName("text1"), this may return more than one element (if there are more then one with the same name).
i think you want this???
function get_value()
{
var inv_nrs;
inv_nrs = document.getElementById('txt1').value;
document.getElementById('txt2').value=inv_nrs;
}
<input type="text" id="txt1" >
<input type="text" id="txt2" onblur="get_value()">
If you search with tagname then you need to insert a tagname:
document.getElementsByTagName('input')[whole_number].value which also
returns a live HTMLCollection
Eg. document.getElementsByTagName("input")[0].value; ,if this is the first textbox in your page.
You can get the value of an html element also on different ways:
document.getElementsByName('text1')[whole_number].value which also
returns a live NodeList
Eg. document.getElementsByName("searchTsxt")[0].value; if this is the
first textbox with name 'searchtext' in your page.
You can also get element by Id:
document.getElementById('IDHere').value to get the value of desired
box
You can also get it by way of Classname:
Use document.getElementsByClassName('class_name')[whole_number].value
which returns a Live HTMLCollection
Good luck

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";

Styling input field of dynamic ID using getElementById

I have some input fields that has its id's number changes dynamically.
For example, the below code shows an input field that has "id="field14". The word (field) in the id does not change, but the (number) is changing dynamically. So it may be field14, field13, or field20, etc, and there is no limit for numbers.
<input type="text" name="field[14]" id="field14" value="" size="30" style="height: 24px;">
I'm using the following code to style the input field:
document.getElementById("field14").style.height = "24px";
Note, the application's PHP code is encoded & I'm editing in smarty template.
The input code in the template is like this: {$field.input} So when I inspect element on the live page it shows the above code of the input with the dynamic number of the id.
I want a way that allow me to style any input field of the page that starts with the word (field) and ends with a dynamic (number). Any suggestions please?
For a pure CSS approach, I would check the name instead, so you should only look for input elements whose attribute starts with field[ and ends with a closing bracket ].
e.g.
input[name^="field["][name$="]"] {
...
}
From the code you posted you can reasonably suppose that the name of all the elements containing a numeric index inside brackets [] are also the same elements with that dynamic index as a part of your id.
otherwise you may write a more complex set of selectors looking for an id starting with field and ending with a digit [0..9]
e.g.
input[id^="field"][id$="0"],
input[id^="field"][id$="1"],
input[id^="field"][id$="2"],
input[id^="field"][id$="3"],
input[id^="field"][id$="4"],
input[id^="field"][id$="5"],
input[id^="field"][id$="6"],
input[id^="field"][id$="7"],
input[id^="field"][id$="8"],
input[id^="field"][id$="9"] {
...
}
or even combine both the methods
input[name^="field["][name$="]"][id$="0"],
input[name^="field["][name$="]"][id$="1"],
...
input[name^="field["][name$="]"][id$="9"] {
...
}
You can use an attribute selector:
input[id^=field] {
/* Styles */
}
It will match all input elements whose id attribute begins with "field". Using some separator between "field" and the number may be better to prevent matching things like "fieldone".
input[id^=field] {
background: red;
}
<input id="field1" />
<input id="field2" />
<input id="field3" />
<input id="field15" />
<input id="field99" />
i strongly recommand using a class attribute:
HTML
<input type="text" class="fields" name="field[14]" id="field14" value="" size="30" style="height: 24px;">
CSS
.fields {
/*style*/
}
I want a way that allow me to style any input field of the page that
starts with the word (field) and ends with a dynamic (number). Any
suggestions please?
This is a very specific question that wants us to key on the fact that the id starts with "field" and ends in a dynamic number. IMHO this solution answers your question exactly as asked using only CSS, plus it doesn't require you to change your HTML or add a class attribute (although this would be much better).
This CSS code will find any <input> tag that has an id starting with "field" and ending in a number. It will also exclude those that start with "field" but do not end in a number.
input[id^='field'][id$='0'],input[id^='field'][id$='1'],input[id^='field'][id$='2'],input[id^='field'][id$='3'],input[id^='field'][id$='4'],input[id^='field'][id$='5'],input[id^='field'][id$='6'],input[id^='field'][id$='7'],input[id^='field'][id$='8'],input[id^='field'][id$='9']
{
// styling code
}
Demo code: http://jsfiddle.net/Drakes/7wpnL/671/
If you need JS approach:
http://codepen.io/knitevision1/pen/LEaXxW
var num = 2;
document.getElementById("input" + num).style.backgroundColor = "blue";
If I get you right, you need all your new input look somewhat unique or something.
You can think of getting a number of the currently presenting inputs, then get the last of them, then attach your style based on what you want it to look like.
Using jquery:
var inputs = [];
function getFields(){
$('input').each(function() {
if($(this).attr('id').substring(0,5)=='field'){
inputs.push($(this));
}
});
}
you can modify each input inside the "each" loop, or you can use the "inputs" variable.
Demo: http://jsbin.com/kubaku/1/edit?html,js,output
JS
var inputs = document.getElementsByTagName('input');
var ID = 'field';
var i;
for(i = 0; i < inputs.length; i++) {
var input = inputs[i];
var regex = new RegExp("^" + ID);
if(regex.test(input.id)) {
input.style.border = '1px solid #c00';
}
}

Getting the correct name of clicked input from a list JQUERY

I'm struggling to use jquery to identify the button i'm clicking.
I've a dynamically generated list categories along with a Remove button to delete it from the database.
My inputs are like this:
<input id="deletesector" class="deletesector" type="submit" name="deletesector-4" value="Remove"></input>
<input id="deletesector" class="deletesector" type="submit" name="deletesector-5" value="Remove"></input>
<input id="deletesector" class="deletesector" type="submit" name="deletesector-6" value="Remove"></input>
my script listens for a .deletesector click and then get the attr name. however, it returns the name of deletesector-4 no matter which of the 3 buttons is clicked.
How do I fix this so that if "deletesector-5" is clicked it identifies it as such.
$(".deletesector").click(function() {
//store the id
var name = $("input#deletesector").attr('name');
//create the post variable string
var dataString = 'serviceid='+ name;
alert (dataString);
Use this inside the anonymous function for the click-handler:
$(".deletesector").click(function(){
var name = this.name
});
The reason you always got the name of deleteselector4 is because that's the first (but not the only) element with the id of deleteselector, an id must be unique for HTML to be valid. With that in mind id selectors only ever look for one element when they search by id, and stop at that first element, assuming it's the only element with that id (as it should be).
Given that the id in your HTML is the same as the class, remove the id since it's doing nothing useful, and actively harming your HTML's validity.
References:
Element identifiers: the id and class attributes.
Use:
$(".deletesector").click(function(){
var name = $(this).attr('name');
// your stuff here
});
this in a jQuery event refers to the element that was clicked on.
Also, your duplicate ids will mess stuff up.
See this JSFiddle for a working example.
First of all, you have some duplicated ids.
Here is the fixed code:
<input id="deletesector-4" class="deletesector" type="submit" name="deletesector-4" value="Remove"></input>
<input id="deletesector-5" class="deletesector" type="submit" name="deletesector-5" value="Remove"></input>
<input id="deletesector-6" class="deletesector" type="submit" name="deletesector-6" value="Remove"></input>
Then you jQuery could be like this:
$(".deletesector").click(function(ev) {
// CHECK THIS $(ev.target) element, very useful!
elementClicked = $(ev.target);
var name = elementClicked.attr('name');
var dataString = 'serviceid='+ name;
alert (dataString);
});
Here is a JSFiddle that shows your example working.

Count Dynamically created html elements with jquery

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

Categories

Resources