Suppose I have the following code:
<div id="Car1Container">
<label id="Car1YearLabel" for="Car1Year">Year</label>
<input id="Car1Year" name="Car1Year" type="text" maxlength="4" onfocus="FieldOnFocus(this)" onkeydown="FieldOnKeyDown(this)" onkeyup="FieldOnKeyUp(this)" onblur="FieldOnBlur(this)"/>
<label id="Car1MakeLabel" for="Car1Make">Make</label>
<input id="Car1Make" name="Car1Make" type="text" maxlength="15" onfocus="FieldOnFocus(this)" onkeydown="FieldOnKeyDown(this)" onkeyup="FieldOnKeyUp(this)" onblur="FieldOnBlur(this)"/>
<label id="Car1ModelLabel" for="Car1Model">Model</label>
<input id="Car1Model" name="Car1Model" type="text" maxlength="16" onfocus="FieldOnFocus(this)" onkeydown="FieldOnKeyDown(this)" onkeyup="FieldOnKeyUp(this)" onblur="FieldOnBlur(this)"/>
<button id="AddVehicleButton1" name="AddVehicleButton1" type="button" onclick="AddVehicle()">Add Vehicle</button>
</div>
<div id="Car2Container" style = "display: none;">
<label id="Car2YearLabel" for="Car2Year">Year</label>
<input id="Car2Year" name="Car2Year" type="text" maxlength="4" onfocus="FieldOnFocus(this)" onkeydown="FieldOnKeyDown(this)" onkeyup="FieldOnKeyUp(this)" onblur="FieldOnBlur(this)"/>
<label id="Car2MakeLabel" for="Car2Make">Make</label>
<input id="Car2Make" name="Car2Make" type="text" maxlength="15" onfocus="FieldOnFocus(this)" onkeydown="FieldOnKeyDown(this)" onkeyup="FieldOnKeyUp(this)" onblur="FieldOnBlur(this)"/>
<label id="Car2ModelLabel" for="Car2Model">Model</label>
<input id="Car2Model" name="Car2Model" type="text" maxlength="16" onfocus="FieldOnFocus(this)" onkeydown="FieldOnKeyDown(this)" onkeyup="FieldOnKeyUp(this)" onblur="FieldOnBlur(this)"/>
<button id="AddVehicleButton2" name="AddVehicleButton2" type="button" onclick="AddVehicle2()">Add Vehicle</button>
</div>
Currently, AddVehicle() just changes the Car2Container style to 'block'. I have a finite number of these and I want it to be dynamic. I have some code to attempt to write it to a page, but it erases everything on the page and doesn't really work.
I want to write an AddVehicle() function to duplicate the Car1Container and place it right below in the HTML document (except all the 1s become 2s). This is turning out to be quite a challenge! Can anyone help get me moving in the right direction?
Thanks!
You can use cloneNode(true) for cloning the block, then go through childNodes property to find all the children (maybe recursively) and replace their ids and names.
Added: Here's a working example:
var container = document.getElementById('Car1Container');
var copy = container.cloneNode(true);
container.parentNode.appendChild(copy);
The jQuery Clone() will do this rather nicely. Granted, it won't increase the ID's, but I'm not convinced it needs to. Just name the fields CarYear, CarMake etc. When the values are posted to the server, if you've duplicated three of the div's, they'll be comma-separated. If necessary, you could iterate through the items and change the id's manually.
I think the jquery clone function would be useful for this.
If you want to use jquery you can just do:
var index = 1;
function copycar(){
index++;
var $tmp = $("#Car1Container").clone();
$tmp.children().each(function(){
var oldID = $("this").attr("id");
var newId = oldId.substring(0,3)+index+oldId.substring(4);
$(this).attr("id", newId);
}
$("#Car1Container").after($tmp);
}
Without using jQuery, just raw JavaScript you could use insertAdjacentHTML.
Example:
document.getElementById(‘ID’).insertAdjacentHTML(position, markup)
where position can be "beforebegin", "afterbegin", "beforeend", or "afterend"
http://lionheart.sg/insertadjacenthtml/
This should be faster than the clone method in jQuery.
Related
I have a list of textbox which is dynamically generated and and named with multi-dimensional array for posting to php later.
<input type="text" name="node['A11']['in']">
<input type="text" name="node['A11']['out']">
<input type="text" name="node['X22']['in']">
<input type="text" name="node['X22']['out']">
<input type="text" name="node['C66']['in']">
<input type="text" name="node['C66']['out']">
However, before the values get posted, i am trying to get the value of the specific textbox and do the validation.
var nodeValue = document.getElementsByName("node['X22']['in']").value;
alert(nodeValue);
Tried the above but it is not working. May i know is there a good way to parse trough the textbox list and get the specific textbox's value, let's say for 'X22' -> 'in'?
getElementsByName returns not a single element, but array-like object. Access the [0] indexed element of the result.
If you have unique elements, it will be better to get them by id (getElementById) which returns a single element.
var nodeValue = document.getElementsByName("node['X22']['in']")[0].value
// ----^^^----
alert(nodeValue);
<input type="text" name="node['A11']['in']">
<input type="text" name="node['A11']['out']">
<input type="text" name="node['X22']['in']" value='SomeValue'>
<input type="text" name="node['X22']['out']">
<input type="text" name="node['C66']['in']">
<input type="text" name="node['C66']['out']">
you need a value to get one
<html>
<head></head>
<body>
<input type="text" name="node['A11']['in']">
<input type="text" name="node['A11']['out']">
<input type="text" name="node['X22']['in']">
<input type="text" name="node['X22']['out']">
<input type="text" name="node['C66']['in']">
<input type="text" name="node['C66']['out']">
</body>
<script>
parse = function(){
var nodeValue = document.getElementsByName("node['X22']['in']");
console.log(nodeValue[0]);//to demonstrate that a nodelist is indeed returned.
}
parse()
</script>
</html>
You could use the id attribute and give it an identifier.
var nodeValue = document.getElementById("X22in").value;
console.log(nodeValue);
<input type="text" id="X22in" name="node['X22']['in']" value="foo">
<!-- ^^^^^^^^^^ -->
I did a script using JQUERY 1.6 to round input, so when I type a long number my script will automatically round 2 decimals.
But is only working with the first input and is not working with other inputs with the same input ID
Here is the live demo
<script>
jQuery("#round_inputs").live("change", function(){
input_values = parseFloat(jQuery("#round_inputs").val());
if (isNaN(input_values)) input_values = "";
jQuery("#round_inputs").val(input_values.toFixed(2));
});
</script>
<input id="round_inputs" size="20" style="text-align:right" type="text"/><br/>
<input id="round_inputs" size="20" style="text-align:right" type="text"/><br/>
<input id="round_inputs" size="20" style="text-align:right" type="text"/><br/>
Please somebody can help me?
As was pointed out in the comments, ID must be unique, so use classes instead. And you need to refer to each input with jQuery(this), otherwise you're just referring to the first element with the class:
jQuery(".round_inputs").live("change", function () {
input_values = parseFloat(jQuery(this).val());
if (isNaN(input_values)) input_values = "";
jQuery(this).val(input_values.toFixed(2));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<input class="round_inputs" size="20" style="text-align:right" type="text" />
<br/>
<input class="round_inputs" size="20" style="text-align:right" type="text" />
<br/>
<input class="round_inputs" size="20" style="text-align:right" type="text" />
Also, as of jQuery 1.7 .live() has been deprecated in favor of .on(), so consider updating your code accordingly.
First off. ID's in a HTML page is supposed to be unique.
Use classes instead.
Avoid inline styles , use CSS to keep your HTML clean.
Inside the change handler use $(this) to target the element that triggered the event.
Use on instead of live which is now deprecated.
JS
$(".round_inputs").on("change", function () {
var input_values = parseFloat($(this).val());
if (isNaN(input_values)) input_values = "";
$(this).val(input_values.toFixed(2));
});
HTML
<input class="round_inputs" size="20" type="text" />
<br/>
<input class="round_inputs" size="20" type="text" />
<br/>
<input class="round_inputs" size="20" type="text" />
<br/>
CSS
.round_inputs {
text-align:right
}
Check Fiddle
When using ID Selectors, jQuery will only ever return the first instance. You should use a classname selector for this:
<input id="round_input1" class="round-input" size="20" style="text-align:right" type="text"/><br/>
And change your jQuery selector to: jQuery('.round-input')
https://api.jquery.com/id-selector/
I DID search but couldn't find anything that helped me to figure out my particular issue. I've got textboxes for a customer address, and textboxes for a business address, and a checkbox to mark if the address should be the same. I need to get the Checkbox to fill the business address with the customer address onclick and unfill them on onclick. I've tried using a few different ways with jquery and straight javascript DOM manipulation, the most success I've had is in the following code, it only fills the biz_street textbox with the cust_street value though, and I don't understand why. Some help would be greatly appreciated, either in jquery or straight javascript, can't use php (sadly).
Here it is on jsfiddle (as suggested by rjmunro, good idea :) ): http://jsfiddle.net/yN73w/1/ not working at all
Here is the jquery:
$("#same_box").click(function () {
var v = $("#cust_street").val();
var x = $("#cust_city").val();
var y = $("#cust_state").val();
var z = $("#cust_zip").val();
$("#biz_street").val(v);
$("#biz_city").val(x);
$("#biz_state").val(y);
$("#biz_zip").val(z);
});
Or more simply:
$("#same_box").click(function () {
$("#biz_street").val($("#cust_street").val());
$("#biz_city").val($("#cust_city").val());
$("#biz_state").val($("#cust_state").val());
$("#biz_zip").val($("#cust_zip").val());
});
And the HTML:
<label id="cus_street_label">Street</label></br>
<input type="text" name="cust_street" id="cust_street" style="width:90%" /></br>
<div id="cus_city">
<label id="cus_city_label">City</label></br>
<input type="text" name="cust_city" id="cust_city" style="width:100%" /></br>
</div>
<div id="cus_state">
<label id="cus_state_label">State</label></br>
<input type="text" name="cust_state" id="cust_state" style="width:70%" /></br>
</div>
<div id="cus_zip">
<label id="cus_zip_label">Zip</label></br>
<input type="text" name="cust_zip" id="cust_zip" style="width:65%" /></br>
</div>
<input type="checkbox" name="same_box" id="same_box" >Address Same as Customer</input></br>
<label id="biz_street_label">Street</label></br>
<input type="text" name="biz_street" id="biz_street" style="width:90%" /></br>
<div id="biz_city">
<label id="biz_city_label">City</label></br>
<input type="text" name="biz_city_box" id="biz_city_box" style="width:100%" /></br>
</div>
<div id="biz_state">
<label id="biz_state_label">State</label></br>
<input type="text" name="biz_state_box" id="biz_state_box" style="width:70%" /></br>
</div>
<div id="biz_zip">
<label id="biz_zip_label">Zip</label></br>
<input type="text" name="biz_zip_box" id="biz_zip_box" style="width:80%" /></br>
</div>
Thank you very much for any help, and I apologize if I missed a topic like this in my searching.
(Also, unrelated, but why doesn't function formReset() {
document.getElementById("customer").reset();
} work in firefox? It only seems to work in chrome)
(you need to select jQuery in your JSFiddle, like http://jsfiddle.net/7HGNx/)
Your code is referring to biz_city but the element's id is biz_cty_box.
You probably don't want to attach to click, you probably want listen to the change event, as this will fire when the option is changed without the mouse. I would also check that the change has been ticking the box, not unticking the box.
$("#same_box").change(function (e) {
if ($(this).is(":checked")) {
.
.
.
}
}
can anyone explain me what happen here??
i have this html code:
<div class="calculadora">
<div class="clear campos">
<label>Amount</label>
<input class="fi" id="amount" type="text" name="amount" value=""/>
</div>
<div class="clear campos">
<label>Down Payment</label>
<input class="fi" id="downPay" type="text" name="downPay" value=""/>
</div>
<div class="clear campos">
<label>Years</label>
<input class="fi" id="years" type="text" name="years" value=""/>
</div>
<div class="clear campos">
<label>Rate</label>
<input class="fi" id="rate" type="text" name="rate" value=""/>
</div>
<input id="cal" type="button" value="cacular"/>
<div class="result"></div>
</div>
And i'm making a jquery plugin, but i need to get all the attr('value') of each input, and i´m doing this way:
this.each(function(){
var obj = $(this),
vacio = parseFloat( $('.fi', obj).attr('value'));
// some code...
But what happens it's that only get the first value of the first input... why??
BUT!! if i make this way :
var s = $('.fi', obj).each(function(){
alert ($(this).attr('value'))
});
it workss!!! Why?? this is good???
Tks in advance if anyone can explain to me.
.attr() returns the value of the specified attirbute from the first element in the collection is called upon.
From the doc:
Get the value of an attribute for the first element in the set of matched elements.
When you make it the other way, you are extracting the value attribute data for each element in the matched set.
One way to achieve what you're after could be done by using the .map() function, which returns a jquery array:
var vals = $('.fi', obj).map(function(){
return this.value;
});
To transform it to a pure javascript array, you use vals.toArray();
Note: no need for jquery to get the value of an input because this in event handlers and in iteration on elements is the current DOMElement, so you can just do this.value.
I have a form where users can add input fields with jQuery.
<input type="text" id="task" name="task[]" />
After submitting the form I get an array in PHP.
I want to handle this with the $.ajax() but I have no idea how to turn my <input>s to an array in jQuery.
Using map:
var values = $("input[id='task']")
.map(function(){return $(this).val();}).get();
If you change or remove the id (which should be unique), you may also use the selector $("input[name='task\\[\\]']")
Working example: http://jsbin.com/ixeze3
For multiple elements, you should give it a class rather than id eg:
<input type="text" class="task" name="task[]" />
Now you can get those using jquery something like this:
$('.task').each(function(){
alert($(this).val());
});
Firstly, you shouldn't have multiple elements with the same ID on a page - ID should be unique.
You could just remove the id attribute and and replace it with:
<input type='text' name='task'>
and to get an array of the values of task do
var taskArray = new Array();
$("input[name=task]").each(function() {
taskArray.push($(this).val());
});
To catch the names array, i use that:
$("input[name*='task']")
You can't use same id for multiple elements in a document. Keep the ids different and name same for the elements.
<input type="text" id="task1" name="task" />
<input type="text" id="task2" name="task" />
<input type="text" id="task3" name="task" />
<input type="text" id="task4" name="task" />
<input type="text" id="task5" name="task" />
var newArray = new Array();
$("input:text[name=task]").each(function(){
newArray.push($(this));
});
HTML:
<input type="text" name="task[]" class="form-control" id="task">
JS:
var tasks= new Array();
$('input[name^="task"]').each(function()
{
tasks.push($(this).val());
});
if you want selector get the same id, use:
$("[id=task]:eq(0)").val();
$("[id=task]:eq(1)").val();
etc...
You can use jquery.serializeJSON to do this.
Q:How to access name array text field
<input type="text" id="task" name="task[]" />
Answer - Using Input name array :
$('input[name="task\\[\\]"]').eq(0).val()
$('input[name="task\\[\\]"]').eq(index).val()