JQuery ignoring form element - javascript

I have this JQuery:
$(document).ready(function() {
$("#generate").click(function() {
var texts = [];
alert();
$("form label").each(function() {
var oLabel = $(this);
var oInput = oLabel.next();
texts.push(oLabel.text() + " " + oInput.val());
});
texts[0] += texts[1];
texts[2] += texts[3];
for(i=3;i<texts.length;i++)
texts[i-1] = texts[i];
texts[texts.length-1] = null;
$("#cont").html(texts.join("<br />"));
});
});
What it do is it reads form elements then types them as regular text (there is a purpose for this).
And this is how my form looks like ...
<div id="cont" style="float:right; width:75%; height:auto">
<form onSubmit="return generate();">
<label class="itemLabel" for="name">Name : </label>
<input name="name" type="text" class="itemInput" value="<? echo $queryB[1]; ?>" readonly="readonly" />
<label># Some Text</label><br />
<label for="priPhone" class="itemLabel">Customer Telephone Number : </label>Phone#
<input name="priPhone" type="text" class="itemInput" readonly="readonly" value="<? echo $queryB[2]; ?>" />
<label for="secPhone"> // Mobile#</label>
<input name="secPhone" type="text" class="itemInput" readonly="readonly" value="<? echo $queryB[3]; ?>" /><br />
<label class="itemLabel" for="email">Customer Email Address : </label>
<input name="email" type="text" class="itemInput" readonly="readonly" value="<? echo $queryB[4]; ?>" /><br />
<label>***************</label><br />
<label>Best Regards,</label><br />
<input name="another_field" type="text" /><br />
<label>last thing</label><br />
<button type="button" id="generate">Generate</button>
</form>
</div>
now, when I click the button "Generate", everything goes well except that it ignores "another_field" and doesn't get its value
Anyone got an idea to solve this? (Note: This piece of code will be running on around 25 forms so I need to have it working.)
UPDATE:
Sample output:
Name : username # Some Text
Customer Telephone Number : 90237590 // 3298579
Customer Email Address : email#host.com
***************
Best Regards,
last_field
last thing
Workaround
Since I'm having all the forms have the same ending, I've been able to get to this code:
texts[0] += " " + texts[1];
texts[1] = texts[2] + " " + texts[3];
for(i=4;i<texts.length;i++)
texts[i-2] = texts[i];
texts[texts.length-2] = texts[texts.length-3];
texts[texts.length-3] = $("#agent").val() ;
texts[texts.length-1] = null;
It solved the problem, but I'm looking for a better way to accomplish this.

Try this javascript:
$(document).ready(function() {
$("#generate").click(function() {
var texts = [];
$("form").children().each(function() {
var el = $(this);
if (el.prop('tagName') == "LABEL") texts.push(el.text());
if (el.prop('tagName') == "INPUT") texts.push(el.val());
if (el.prop('tagName') == "BR") texts.push("<br />");
});
$("#cont").html(texts.join(""));
});
});
Working example here:
http://jsfiddle.net/Q5AD4/6/

Your <br/> tag is the next tag after the label before "another_field". You should probably make your next call something like:
var oInput = oLabel.next('input');

Related

check input number whether bigger than certain value by using javascript

I am trying to do some calculation in page, however, it doesn't work, I have tried the following code, does anyone can tell me the correct answer?
For example, when I enter a number then it will do one of the calculation.
<table><tr><td>
<input name="per_pax" size="2" style="border-style:none" type="text" id="per_pax" value="">
</td><td>
<input name="sum_tlcost" type="hidden" id="sum_tlcost" value="<?php echo $tl_cost;?>">
<input name="sum_htl_pp" type="hidden" id="sum_htl_pp" value="<?php echo $sum_htl_pp;?>">
<input name="sum_coach" type="hidden" id="sum_coach" value="<?php echo $sum_coach;?>">
<input name="pax" size="5" readonly="readonly" type="text" id="pax" value="">
</td></tr></table>
<script>
$(document).ready(function () {
var total = Number($("#per_pax").val());
if(total >= 20) {
$("#sum_tlcost,#sum_htl_pp,#sum_coach,#per_pax").keyup(function () {
if (parseInt($("#per_pax").val()) >= 20) {
$("#pax").val(Math.round(Number($("#sum_htl_pp").val()) + Number($("#sum_tlcost").val()) / Number($("#per_pax").val()) + Number($("#sum_coach").val()) / Number($("#per_pax").val()));
)}else{
$("#pax").val(Math.round(Number($("#sum_htl_pp").val()) + Number($("#sum_tlcost").val()) + Number($("#sum_coach").val())))
}
})}})
</script>
I'm not overly fond of the jquery keyup calls... so here's a snippet that should call your function using normal DOM event calls. The input event triggers as they type.. which should be similar to what you're trying to do with the keyups... I also cleaned up the function itself to make it more readable for presentation.
function onInputChange() {
var perPax = parseInt($("#per_pax").val());
var tlCost = Number($("#sum_tlcost").val());
var htlPP = Number($("#sum_htl_pp").val());
var coach = Number($("#sum_coach").val());
var newValue = 0;
if (perPax < 20) {
newValue = (htlPP + tlCost) / (perPax + (coach / perPax));
} else {
newValue = htlPP + tlCost + coach;
}
$("#pax").val(Math.round(newValue))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input name="per_pax" size="2" style="border-style:none" type="text" id="per_pax" value="" oninput="onInputChange()">
</td>
<td>
<input name="sum_tlcost" type="hidden" id="sum_tlcost" value="<?php echo $tl_cost;?>">
<input name="sum_htl_pp" type="hidden" id="sum_htl_pp" value="<?php echo $sum_htl_pp;?>">
<input name="sum_coach" type="hidden" id="sum_coach" value="<?php echo $sum_coach;?>">
<input name="pax" size="5" readonly="readonly" type="text" id="pax" value="">
</td>
</tr>
</table>

How to determine if the input is of array type in javascript?

<input type="text" name="members[0].name">
<input type="text" name="members[0].address">
Javascript code :
var input_text;
var inputs=document.querySelectorAll("input[type=text],textarea, select");
_.each(inputs, function(e, i) {
var keyName = $(e).attr("name");
if (typeof keyName != "undefined") {
var text = $(e).parent().find('label').text();
if ($(e).is('select')) {
input_text = input_text + "<tr><td>" + text + "</td><td> " + $(e).find(':selected').text() + "</td></tr>";
}
else {
input_text = input_text + "<tr><td>" + text + "</td><td> " + $(e).val() + "</td></tr>";
}
}
});
console.log(input_text);
As You can see, I m getting the values of all the inputs in $(e).val() except those above mentioned inputs.
Those inputs aren't an "array" in the browser. They just use a naming convention in their name which is used by some server-side handling (for instance, in PHP) to organize the form data for you when it's submitted.
I don't know what you mean by "previewing," but you can see the values of those elements by simply looping through the elements of your form (yourForm.elements), or by using yourForm.querySelectorAll("input[type=text]") (or $(yourForm).find("input[type=text]") using jQuery — I missed the jquery tag on your question at first).
Example of theForm.elements:
document.querySelector("form input[type=button]").addEventListener("click", function() {
var form = document.getElementById("the-form");
Array.prototype.forEach.call(form.elements, function(element) {
if (element.type === "text") {
console.log(element.name + " = " + element.value);
}
});
});
<form id="the-form">
<input type="text" name="members[0].name" value="name 0">
<input type="text" name="members[0].address" value="address 0">
<input type="text" name="members[1].name" value="name 1">
<input type="text" name="members[1].address" value="address 1">
<input type="text" name="members[2].name" value="name 2">
<input type="text" name="members[2].address" value="address 2">
<div>
<input type="button" value="Show">
</div>
</form>
Example of theForm.querySelectorAll:
document.querySelector("form input[type=button]").addEventListener("click", function() {
var form = document.getElementById("the-form");
Array.prototype.forEach.call(form.querySelectorAll("input[type=text]"), function(element) {
console.log(element.name + " = " + element.value);
});
});
<form id="the-form">
<input type="text" name="members[0].name" value="name 0">
<input type="text" name="members[0].address" value="address 0">
<input type="text" name="members[1].name" value="name 1">
<input type="text" name="members[1].address" value="address 1">
<input type="text" name="members[2].name" value="name 2">
<input type="text" name="members[2].address" value="address 2">
<div>
<input type="button" value="Show">
</div>
</form>
Example of $(theForm).find:
$("form input[type=button]").on("click", function() {
var form = document.getElementById("the-form");
$(form).find("input[type=text]").each(function() {
console.log(this.name + " = " + this.value);
});
// Of course, we could have just used `$("#the-form input[type=text]").each`...
// but I was assuming you'd already have `form`
});
<form id="the-form">
<input type="text" name="members[0].name" value="name 0">
<input type="text" name="members[0].address" value="address 0">
<input type="text" name="members[1].name" value="name 1">
<input type="text" name="members[1].address" value="address 1">
<input type="text" name="members[2].name" value="name 2">
<input type="text" name="members[2].address" value="address 2">
<div>
<input type="button" value="Show">
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
So many ways to get the input type values using formID
$('#formId input, #formId select').each(
function(index){
var input = $(this);
}
);
OR
var formElements = new Array();
$("form :input").each(function(){
formElements.push($(this));
});
OR
var $form_elements = $("#form_id").find(":input");
hope it helps you.
You can use serializeArray or serialize for it .
$("form").serializeArray();
The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. Doc

Selecting the correct form in javascript

I have an HTML form with at least two forms in, each with the class 'myform' applied. The input buttons in each have a different id, and once clicked should send the data to a database. The problem is the javascript, which stops the refresh and controls buttons states doesn't select the right form - it always sends the details of the form closest to the script... here are the html forms.
<div class="booking_box">
<form method="post" class='myform'>
<button class="button" id='b2' name = "8">Book room 8</button>
<input type="hidden" name="salutation" value="<?php echo $_SESSION["salutation"]?>">
<input type="hidden" name="firstname" value="<?php echo $_SESSION["firstname"]?>">
<input type="hidden" name="room" value="8">
<input type="hidden" name="period" value="1">
</form>
</div>
<div class="booking_box">
<form method="post" class='myform'>
<button class="button" id='b3' name = "7">Book room 7</button>
<input type="hidden" name="salutation" value="<?php echo $_SESSION["salutation"]?>">
<input type="hidden" name="firstname" value="<?php echo $_SESSION["firstname"]?>">
<input type="hidden" name="room" value="7">
<input type="hidden" name="period" value="1">
</form>
</div>
Here is the script at the bottom of the page. I've tried '.closest' and '.parent' but nothing seems to work. I've also tried adding these to the '$.post' section, but then the data is sent to the DB but it's empty fields. Confused...
<script>
$("button").click(function() {
var myID = ($(this).attr('id'));
var theName = ($(this).attr('name'));
var isAdd = $("#" + myID).text();
if (isAdd == "Book room " + theName){
$('#' + myID).text(isAdd ? 'Cancel room' + theName : 'Book room ' + theName);
$('#' + myID).closest('.myform').attr('action', isAdd ? 'bookRoom.php' : 'update.php');
} else {
$('#' + myID).text(isAdd ? 'Book room ' + theName : 'Cancel room ' . theName);
$('#' + myID).closest('.myform').attr('action', isAdd ? 'update.php' : 'bookRoom.php');
}
$('.myform').submit(function(){
return false;
});
$.post(
$('.myform').attr('action'),
$('.myform :input').serializeArray(),
function(result){
$('#result').html(result);
}
);
});
</script>
As always, any help would be massively appreciated!
You should be able to use $(this).closest(".myform") to get the form that should be submitted.
It's also not necessary to use $("#" + myID), since that's the same as $(this).
And the submit handler that prevents normal submission should not be inside the click handler.
$('.myform').submit(function(){
return false;
});
$("button").click(function() {
var theName = ($(this).attr('name'));
var isAdd = $(this).text();
var form = $(this).closest(".myform");
if (isAdd == "Book room " + theName){
$(this).text(isAdd ? 'Cancel room' + theName : 'Book room ' + theName);
form.attr('action', isAdd ? 'bookRoom.php' : 'update.php');
} else {
$(this).text(isAdd ? 'Book room ' + theName : 'Cancel room ' . theName);
form.attr('action', isAdd ? 'update.php' : 'bookRoom.php');
}
$.post(
form.attr('action'),
form.serialize(),
function(result){
$('#result').html(result);
}
);
});
Use the event to get the form from the button. Define "e" in your function and e will be the event, e.target is the button, and e.target.form is the form. (tested with jquery 2.2.4)
$("button").click(function(e) {
var myID = ($(this).attr('id'));
var theName = ($(this).attr('name'));
var isAdd = $("#" + myID).text();
var frm = e.target.form;
You could either choose to set the id of both forms, for example:
<form method="post" class='myform' id="form1">...</form>
<form method="post" class='myform' id="form2">...</form>
Or if you do not want to set an id, you can use :nth-child, for example:
$('.myform:nth-child(1)') //will select the 1st form
$('.myform:nth-child(2)') //will select the 2nd form
just add another class to forms like
<div class="booking_box">
<form method="post" class='myform 8'>
<button class="button" id='b2' name = "8">Book room 8</button>
<input type="hidden" name="salutation" value="<?php echo $_SESSION["salutation"]?>">
<input type="hidden" name="firstname" value="<?php echo $_SESSION["firstname"]?>">
<input type="hidden" name="room" value="8">
<input type="hidden" name="period" value="1">
</form>
</div>
<div class="booking_box">
<form method="post" class='myform 7'>
<button class="button" id='b3' name = "7">Book room 7</button>
<input type="hidden" name="salutation" value="<?php echo $_SESSION["salutation"]?>">
<input type="hidden" name="firstname" value="<?php echo $_SESSION["firstname"]?>">
<input type="hidden" name="room" value="7">
<input type="hidden" name="period" value="1">
</form>
</div>
Now in your script, you are already getting the button id as "7" or "8". Use this "myID" for selecting forms.
Add this to your script.
$('.myform').each(function( index ) {
if($(this).hasClass(myID)){
$(this).submit(function(){
return false;
});
}
});
It just iterate over your all form having "myform" as class and check if they are also having a class as "7" or "8" fetched from the button pressed.
https://api.jquery.com/each/
https://api.jquery.com/hasclass/
If you want to get the current form of your buttons, you can use .closest(). When you have the current form, you can extract all the information (input) inside.
You can do this:
$("button").click(function () {
var currentForm = $(this).closest("form");
var actionForm = $(currentForm).attr('action');
$.post(
actionFormF,
$(currentForm).find('input').serializeArray(),
function (result) {
$('#result').html(result);
}
);
});

Input fields value not changing in click function

In my previous code I have used two separate input fields % and $ value. % value code:
<td>
<input name="propertytaxpc" type="text" size="8" maxlength="8" value="<?php echo $dproperty_tax; ?>" onChange="javascript:propertyTaxPcChanged(true)" />
%
</td>
$ value code:
<td>
$
<input name="propertytaxamt" type="text" size="8" maxlength="8" onChange="javascript:propertyTaxAmountChanged(true)" />
</td>
In my new code I have input fields changed the two fields to one field. % and $ values both load single input fields loan. I have set % and $ icon on click. Now input fields default % icon also %. When the user changes icon % to $ the value also needs to change.
<div class="col-md-3 padding-rht">
<input name="propertytaxpc" class="txt" type="text" size="8" maxlength="8" value="<?php echo $dproperty_tax;?>" onChange="javascript:propertyTaxPcChanged(true)" />
</div>
<div class="col-md-1 padding-lft">
<img src="Content/Images/percent.png" onclick="changeColor(event,this.src)" style="cursor:pointer"/>
</div>
function changeColor(event, _src) {
var fname = _src;
var ImageName = fname.substring(fname.lastIndexOf('/') + 1);
//alert(ImageName);
if (ImageName == "percent.png") {
$(event.target).attr("src", "Content/Images/RedDoller.png");
}
else {
$(event.target).attr("src", "Content/Images/percent.png");
}
}
Can any one take look? I have tried many methods, but they're not working? Thanks in advance.
Your question is not very clear, but if I understand correctly I think what you're trying to achieve is for the percent and amount fields to switch visibility according to the $/% image, right?
If so, what you need to do is toggle the two input fields' visibilty, along with changing the image source. Try the code below:
HTML/PHP:
<div class="col-md-3 padding-rht">
<input id="pct" name="propertytaxpc" class="txt" type="text" size="8" maxlength="8" value="<?php echo $dproperty_tax;?>" onChange="javascript:propertyTaxPcChanged(true)" />
<input id="amt" name="propertytaxamt" class="txt" type="text" size="8" maxlength="8" onChange="javascript:propertyTaxAmountChanged(true)" />
</div>
<div class="col-md-1 padding-lft">
<img id="change" src="Content/Images/percent.png" onclick="changeColor(event,this.src)" style="cursor:pointer"/>
</div>
Javascript:
$(document).ready(function() {
$("#amt").hide();
$("#change").click(function() {
changeColor(this);
});
});
function changeColor(elem) {
var $elem = $(elem);
var ImageName = $elem.attr("src");
ImageName = ImageName.substring(ImageName.lastIndexOf('/') + 1);
if (ImageName == "percent.png") {
$elem.attr("src", "Content/Images/RedDoller.png");
} else {
$elem.attr("src", "Content/Images/percent.png");
}
$("#pct, #amt").toggle();
}
An example JS fiddle demonstrating the technique is here: https://jsfiddle.net/ds8txa1j/
This way it works to me. No jquery or extra lib used. There some alert just to check it works...
<div class="col-md-3 padding-rht">
<input name="propertytaxpc" class="txt" type="text" size="8" maxlength="8" value="aaa" onChange="javascript:propertyTaxPcChanged(true)" />
<input name="propertytaxamt" class="txt" type="hidden" size="8" maxlength="8" onChange="javascript:propertyTaxAmountChanged(true)" />
</div>
<div class="col-md-1 padding-lft">
<img src="Content/Images/percent.png" onclick="javascript:changeColor1(this);" style="cursor:pointer"/>
</div>
<script type="text/javascript">
function changeColor1(elem) {
var fname = elem.src;
var ImageName = fname.substring(fname.lastIndexOf('/') + 1);
alert(ImageName);
if (ImageName == "percent.png") {
elem.src = "Content/Images/RedDoller.png";
}
else {
elem.src = "Content/Images/percent.png";
}
alert(elem.src);
}
</script>

Adding XML attribute from array PHP

I am have a dynamic HTML form (jQuery) that a user can add in an ingredient and its quantity, After the user puts in the data I need to save the data as XML. I was thinking of having the quantity as an attribute of the ingredient tag, so for example
<ingredient quantity="250g"> spaghetti </ingredient>
However at the moment I'm not sure how to pass the information in through my array as only a string is allowed as an attribute. I was wondering if anyone had an idea how to do this?
Here are some snippets of my code.
HTML form:
<div id="addIngredient">
<p>
<input type="text" id="ingredient_1" name="ingredient[]" value="" placeholder="Ingredient"/>
<input type="text" id="quantity_1" name="quantity[]" value="" placeholder="quantity"/>
Add
</p>
</div>
<br />
jQuery:
$('#addNewIngredient').on('click', function () {
$('<p> <input id="ingredient_' + i + '" size="40" name="ingredient[]' + '" type=text" value="" placeholder="Ingredient" /><input id="quantity_' + i + '" size="40" name="quantity[]' + '" type=text" value="" placeholder="Quantity" /> Remove </p> ').appendTo(addDiv2);
i++;
return false;
});
PHP:
$ingredients = $xml->createElement('ingredients');
for ($i = 0; $i < 2; $i++) {
$element = $ingredientName[$i];
$ingredient = $xml->createElement('ingredient_name', $element);
$ingredient->setAttribute("quantity", $quantity);
$ingredients->appendChild($ingredient);
}
$recipe->appendChild($ingredients);

Categories