I have code that will automatically add a new similar row defined in form by clicking add button.
<html>
<body>
<form>
<input type="text" name="quantity[]" class="input_text" id="pro"/>
</form>
</body>
</html>
Now I want to access different values of quantity[] in javascript function .
How to access this different values of quantity[] in javascript using it's ID or Name Attribute.
<script>
function abc() {
var id = document.getElementById("pro").value;
}
</script>
You can do something like this.
html:
<form>
<input name="p_id[]" value="0"/>
<input name="p_id[]" value="1"/>
<input name="p_id[]" value="2"/>
</form>
javascript:
var p_ids = document.forms[0].elements["p_id[]"];
alert(p_ids.length);
for (var i = 0, len = p_ids.length; i < len; i++) {
alert(p_ids[i].value);
}
The way to do that with plain JavaScript is to get all the elements with an specific name, as following:
var fields = document.getElementsByName('quantity[]');
Should you want to access an specific value, you could do that as well:
console.log(fields[0].value); // foo
Here's a jsfiddle with a code sample.
HTML:
<form name="order">
<input type="text" name="quantity[]" class="input_text" />
<input type="text" name="quantity[]" class="input_text" />
<input type="text" name="quantity[]" class="input_text" />
</form>
JS:
var elements = document.forms['order'].elements['quantity[]'];
console.log(elements[1].value); // outputs the value of the 2nd element.
demo: http://jsfiddle.net/NDbwt/
$('input[name=quantity]').each(function(){
alert($(this).val())
});
First: id must be unique on page. Otherwise document.getElementById will always return first spotted element with requested id.
In your case, you may do next:
var id = document.getElementsByName("quantity[]")[0].value;
But more safely (I'm not sure if order of items in returned array will always be the same as order in which elements are added) would be to generate ids like pro_0, pro_1, pro_2 etc
You're probably confused by the fact that PHP reads form fields as arrays when you use square brackets on their name. That's only a PHP trick—for JavaScript, [] does not have any special meaning and you can read the items in the usual way:
var values = [];
var fields = document.getElementsByName("quantity[]");
for (var i = 0, len = fields.length; i < len; i++) {
values.push(fields[i].value);
}
alert("Values:\n" + values.join("\n"));
See it in action.
Related
I need to Multiply two user Input Fields and show the results in the third field. The Result field must change when either of the User Input fields are changed.
<input type="number" name="rate" id="rate" />
<input type="number" name="box" id="box" />
The result should be in a third field which changes when either of the two above fields is changed. This totally depends on the user input
<input type="number" name="amount" id="amount" readonly />
I need to do this Multiplication with Jquery.
Thanks in advance
Try this : bind change event listener for rate and box input box and inside it multiply the values to put it in amount input.
$('#rate, #box').change(function(){
var rate = parseFloat($('#rate').val()) || 0;
var box = parseFloat($('#box').val()) || 0;
$('#amount').val(rate * box);
});
DEMO
You can use keyup event to calculate amount as soon as you enter other fields
$('#rate, #box').keyup(function(){
var rate = parseFloat($('#rate').val()) || 0;
var box = parseFloat($('#box').val()) || 0;
$('#amount').val(rate * box);
});
DEMO
Try this : bind input event listener on rate and box input box and inside it multiply the values to put it in amount input.
The input event only fires when the value of the input has changed whereas change only fires once the field has lost focus. input fires immediately
$('#rate, #box').on('input',function(){
var rate = parseFloat($('#rate').val()) || 0;
var box = parseFloat($('#box').val()) || 0;
$('#amount').val(rate * box);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="number" name="rate" id="rate" value=""/>
<input type="number" name="box" id="box" value=""/>
<input type="number" name="amount" id="amount" readonly />
Here is my 2 cents on the above scenario -
http://jsfiddle.net/ak9ejpne/3/
My aim was to keep the code thin & clean and with some MVC flavor.
function Operand(a,b){
this.a = parseInt(a);
this.b = b;
this.c = (this.a)*(this.b);
this.set = function(key,edit){
this[key] = edit;
this.c = (this.a)*(this.b);
};
return this;
}
Do let me know if it is a useful approach for you :)
You can Try It.
<script type="text/javascript">
$("#txtOne,#txtTwo").on("change keyup", function(e){
var txtOne = parseFloat($("#txtOne").val());
var txtTwo = parseFloat($("#txtTwo").val());
var result = txtOne * txtTwo ;
if (!isNaN(result)) {
$("#txtAmount").val(result);
}
});
</script>
I have three inputs for telephone numbers that each have its length of 4,8,4 repectively. I handle the focus of mouse through jQuery when maxlength of input field is reached then focus/jump to the next field.
I also want to do a beside focus to count the digits in each field if they are less then maxlength then append zeros on the left side to make it equal to the maxlength of respective input fields when we echo the entered field. e.g if in first input someone enters only two digits like 47 then the output should be 0047 with two appended zeros on the left side after echo.
Here is my HTML:
<form>
<input type="text" name="area_code" id="area_code" maxlength="4" size="3" /> -
<input type="text" name="number1" id="number1" maxlength="8" size="8" /> -
<input type="text" name="number2" id="number2" maxlength="4" size="3" />
</form>
here is the jquery
<script type="text/javascript" src="js/jquery.autotab-1.1b.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#area_code, #number1, #number2').autotab_magic().autotab_filter('numeric');
});
</script>
You've got PHP and jQuery tags on the question so here's both :
PHP : str_pad
jQuery :
There's no built in function as far as I know so you will have to create one. Here is a question about doing it in javscript.
Adding extra zeros in front of a number using jQuery? the accepted answer should do the trick.
var num1 = $('#number1');
var diff1 = 0;
if (num1.value.length < num1.attr('maxlength'))
{ diff1 = num1.attr('maxlength') - num1.value.length; }
for (var i = 0; i< diff1; i++ ) { num1.val = '0' + num1.val(); }
You could always write a function to do it for you:
$('#area_code, #number1, #number2').blur(function(){
$(this).val(padMe($(this).val(),$(this).attr("maxlength")));
});
function padMe(str,length)
{
var diff = length-str.length;
return (diff>0) ? (new Array( diff+1 ).join("0") + str) : str;
}
Here is my Javascript:
<script>
function disable()
{
document.getElementById("habits").disabled=true;
document.getElementById("habits2").disabled=true;
document.getElementById("exact").disabled=false;
}
function enable()
{
document.getElementById("habits").disabled=false;
document.getElementById("habits2").disabled=false;
document.getElementById("exact").disabled=true;
}
var counter =0;
var i = 0;
function duplicate() {
var original = document.getElementById('div');
var clone = original.cloneNode(true); // "deep" clone
i+=1;
clone.id = "div" + i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
document.getElementById('div' + i).getElementsByTagName('select').name += '_clone' + i;
counter+=1;
}
</script>
and this is my HTML code:
<button id="button" onclick="duplicate()">Add List</button><br><br>
<form id ="form" name="search" method="post" action="test.php">
<div id="div">
<div id="d">
<select name ="select" >
...options...
</select>
</div>
Value:<input type="text" id ="exact">
From: <input type="text" id="habits">
To: <input type="text" id="habits2">
<br>
<input type="button" name="answer" value="Range" onclick="enable()" >
<input type="button" name="answer" value="Exact" onclick="disable()" >
</div>
<br><br>
<input type="submit" name ="search" value="Submit">
</form>
My issue here is that, when I clone the div id=div, all the buttons work for the original one, even the cloned buttons. Another thing is that, when I click the submit button to get the options from the drop-down list(s), but after submission, only the last drop-list is counted (cloned), but I want the original only.
Here is my page after clicking submit:
<?php
$item = $_POST["select"];
echo $item;
?>
How can I solve this? That is, changing the id's and names, and functions working with the cloned elements?
First of all, don't use id's if you want to duplicate things. Use and select by class (I strongly recommend to use jQuery), and use name="some_name[]"
To solve your problem you can do: onclick="javascript:enable(this)" or, if you decide to use jQuery, use `onclick="javascript:jQuery(this)", and then you search for siblings of the current element (don't know the pure js syntax, just the jquery one, if you need help with jquery let me know).
Hope this helps, good luck.
try this one. i have changed the function by adding a line
function duplicate() {
var original = document.getElementById('div');
var clone = original.cloneNode(true); // "deep" clone
i+=1;
clone.attr("id",replace(clone.attr("id"),"div"+i));// change the id of clone div
// clone.id = "div" + i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
document.getElementById('div' + i).getElementsByTagName('select').name += '_clone' + i;
counter+=1;
}
Is it possible?
I want a user to post an array full of 1-5 pieces of data.
At first there would be only one text field on show, but on clicking a 'plus' icon next to it, it would create another text field below it for more user input.
I would also want to have a delete icon next to text boxes 2-5, to remove them if necessary.
My JQuery knowledge is limited, and I can work out how to append text boxes to a list, but not to keep track of them/delete them. Ideally I would also want to pass them as an array to php, so I can easily loop through them.
<input type="text" size="15" maxlength="15" name="1"><img src="add.png" onclick="add();">
<!-- Below is hidden by default, and each one shows on click of the add image -->
<input type="text" size="15" maxlength="15" name="2"><img src="delete.png" onclick="delete(2);">
<input type="text" size="15" maxlength="15" name="3"><img src="delete.png" onclick="delete(3);">
<input type="text" size="15" maxlength="15" name="4"><img src="delete.png" onclick="delete(4);">
<input type="text" size="15" maxlength="15" name="5"><img src="delete.png" onclick="delete(5);">
jQuery clone() is very handy for this. A small example how it could be done (working example on jsfiddle)
<ul>
<li><input type="text" name="textbox[]" /></li>
</ul>
<input type="button" id="addTextbox" value="Add textbox" />
<script type="text/javascript">
$(function(){
$('#addTextbox').click(function(){
var li = $('ul li:first').clone().appendTo($('ul'));
// empty the value if something is already filled in the cloned copy
li.children('input').val('');
li.append($('<button />').click(function(){
li.remove();
// don't need to check how many there are, since it will be less than 5.
$('#addTextbox').attr('disabled',false);
}).text('Remove'));
// disable button if its the 5th that was added
if ($('ul').children().length==5){
$(this).attr('disabled',true);
}
});
});
</script>
For the server-side part, you could then do a foreach() loop through the $_POST['textbox']
As long as you give each text box a name like "my_input[]", then when the form is submitted, PHP can get the answer(s) as an array.
$_REQUEST['my_input']; would be an array of the values stored in each text box.
Source: Add and Remove items with jQuery
Add
Remove
<p><input type="text" value="1" /></p>
<script type="text/javascript">
$(function() { // when document has loaded
var i = $('input').size() + 1; // check how many input exists on the document and add 1 for the add command to work
$('a#add').click(function() { // when you click the add link
$('<p><input type="text" value="' + i + '" /></p>').appendTo('body'); // append (add) a new input to the document.
// if you have the input inside a form, change body to form in the appendTo
i++; //after the click i will be i = 3 if you click again i will be i = 4
});
$('a#remove').click(function() { // similar to the previous, when you click remove link
if(i > 1) { // if you have at least 1 input on the form
$('input:last').remove(); //remove the last input
i--; //deduct 1 from i so if i = 3, after i--, i will be i = 2
}
});
$('a.reset').click(function() {
while(i > 2) { // while you have more than 1 input on the page
$('input:last').remove(); // remove inputs
i--;
}
});
});
</script>
You will need to create DOM elements dynamically. See how it is done for example in this question. Notice that
document.createElement
is faster then using jquery's syntax like
$('<div></div>')
Using that technick, you could create inputs like
<input name="id1"/>
<input name="id2"/>
<input name="id3"/>
<input name="id4"/>
<input name="id5"/>
On submitting your form you'll get all them in your query string like
...id1=someval1&id2=someval2&...
Having that, you could process this query as you want on server side.
<form method="POST" id="myform">
<input />
Add textbox
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#add_textbox').click(function(){
var form=$(this).closest('form');
var count=form.find('input').length();
form.append('<div class="removable_textbox"><input />delete</div>');
$('.delete_input').click(function(){
$(this).find('.removable_textbox').remove();
return false;
});
return false;
});
$('#myform').submit(function(){
var i=1;
$(this).find('input').each(function(){
$(this).attr('name','input-'+i);
i++;
})
});
});
</script>
<?php
if(isset($_POST['input-1'])){
$input_array=$_POST;
}
?>
something like this?
I wrote a litte jQuery plugin called textbox. You can find it here: http://jsfiddle.net/mkuklis/pQyYy/2/
You can initialize it on the form element like this:
$('#form').textbox({
maxNum: 5,
values: ["test1"],
name: "textbox",
onSubmit: function(data) {
// do something with form data
}
});
the settings are optional and they indicate:
maxNum - the max number of elements rendered on the screen
values - an array of initial values (you can use this to pass initial values which for example could come from server)
name - the name of the input text field
onSubmit - onSubmit callback executed when save button is clicked. The passed data parameter holds serialized form data.
The plugin is not perfect but it could be a good start.
How can I extract the value attribute of an input tag? Using SIMPLE HTML DOM
let me give you an example:
<form action="#" method="post" name="test_form" id="test_form">
Name<input type="text" name="name" value="NaMe"/><br />
Address<input type="text" name="address" value="AdDrEsS"/><br />
<input type="hidden" value="sayantest" />
</form>
I want to extract just the value of hidden type input tag, not the others.
You want to put the id (so you can access the value in javascript), as well as a name (if you want to access the value on the server) in the tag you wish to get the value from.
e.g.
<input type="hidden" name="test" id="test" value="sayantest" />
then your javascript is as simple as:
<script type="text/javascript">
var val = document.getElementById('test').value;
alert(val);
</script>
using SIMPLE HTML DOM
Do you mean the PHP library of that name?
If so, you'd have to choose a way to identify the input. If you can't change the markup to add an id or name on the hidden input you want, you'd have to come up with something like “get the first input with type hidden in the form”:
$html= new simple_html_dom();
$html->load('<html><body<form action="#" method="post" name="test_form" id="test_form">Name<input type="text" name="name" value="NaMe"/><br />Address<input type="text" name="address" value="AdDrEsS"/><br /><input type="hidden" value="sayantest" /></form></body></html>');
$input= $html->find('#test_form input[type=hidden]', 0);
$input->value;
The easiest way, as already mentioned, is to give your hidden input an id attribute and then use getElementById and then .value or .getAttribute('value') to select it.
Alternatively, if you want to get the values of all hidden inputs on the page, or can't inject your ID, you could use something like this:
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++){
if(inputs[i].getAttribute('type') == 'hidden'){
alert(inputs[i].getAttribute('value'));
}
}
Here is what I came up with... using exactly what you showed in your initial question. Note that all I did was echo the value of all input hidden, where test_form.htm is your original:
<?php
function scraping_form()
{
// create HTML DOM
$html = file_get_html('test_form.htm');
// get input hidden value
$aObj = $html->find('input[type="hidden"]');
foreach ($aObj as $hKey=>$hidden)
{
$valueAttribute = $hidden->value;
echo "*TEST* ".$hKey.": ".$valueAttribute."<br />";
}
// clean up memory
$html->clear();
unset($html);
return;
}
// -----------------------------------------------------------------------------
// test it!
// user_agent header...
ini_set('user_agent', 'My-Application/2.5');
scraping_form();
?>