dynamically add elements from jquery or javascript - javascript

if a user types in an input say 3 into a text box three small text boxes should be shown below or in a popup through javascript or jquery .How can this be done...
<input type="text" name="order">3</input>
Thanks..

Give the <input/> an id of "order", then it's as simple as:
var order = $('#order'),
container = $('<div/>').insertAfter(order);
order.keyup(function(){
container.html(
Array(Math.abs(~~this.value) + 1).join('<input/>')
);
});
FYI, ~~ (double-bitwise-not) has the effect of getting the number representation of any type (using the internal toInt32 operation) and then flooring it. E.g:
~~'2'; // => 2
~~'2.333'; // => 2
~~null; // => 0
And Math.abs is to protect against negative values, that will throw an error if passed to Array().
DEMO: http://jsbin.com/azexa4

Keep in mind you should probably mask the textbox to allow only numerical entries...Or maybe use a drop down list with a list of numbers to prevent error. But here is a great jquery mask plugin to prevent non-numerical entries.
<input type="text" name="Order" onKeyDown="checkVal(this)">3</input>
<div id="myDiv">
</div>
function checkVal(ctrl){
var val = ctrl.value;
$('myDiv').html(''); // remove existing elements
for (i=0;i<parseInt(val,10);i++){
$('#myDiv').append('<input type="text" />');
}
}

Related

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';
}
}

Change all id's in HTMLDivElement using jQuery

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.

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

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

Simple Maths with jQuery - division

I've got two inputs in a div that I want to divide one by the other.
<div>
<input type="number" id="a"> / <input type="number" id="b">
<input type="submit">
<p class="result">RESULT HERE</p>
</div>
How can the maths of this be done with jquery?
It really depends when you want the calculation to take place, but the maths itself is incredibly simple. Just use the standard division operator, /:
var num1 = $("input[label='a']").val(),
num2 = $("input[label='b']").val(),
result = parseInt(num1, 10) / parseInt(num2, 10);
$(".result").text(result);
I guess it also depends if you only want to support integer division (that's why I've used parseInt - you could use parseFloat if necessary).
Also, as mentioned in the comments on your question, label is not a valid attribute. A better option would be to use id, or if you need to use an arbitrarily named attribute, use HTML5 data-* attributes.
Update based on comments
As you have stated that you want the code to run when a button is clicked, all you need to do is bind to the click event:
$("#someButton").click(function() {
//Do stuff when the button is clicked.
});
You're mixing your markup with your logic. You can't divide HTML elements with each other they are for structural presentation only. Instead, you have to pull their values with javascript, apply the math, and update the HTML with the resulting value.

Categories

Resources