How to properly use javascript with SUBMIT? - javascript

At one point in the last 24 hours, I had a working function called get_contact_info which returned the contents of a series of text inputs.
Suddenly the code stopped returning the values and began returning "undefined" as the element values, though noting had been changed in the code or html.
custom.js contains the following
var first_name, last_name, email, phone_number;
var contact_info = [];
function get_contact_info(){
alert("This is the function called by the button");
}
/* contact_info[0] = document.getElementsByName('fname').value;
contact_info[1] = document.getElementsByName('lname').value;
contact_info[2] = document.getElementsByName('email').value;
contact_info[3] = document.getElementsByName('phone').value;
alert("Name = " + contact_info[0] + " " + contact_info[1]);
alert("Email = " + contact_info[2] + ", Phone Number " + contact_info[3]);
};*/
}());
My html is the following:
<form>
<table>
<tbody>
<tr><div class="custom text" style="color: red"><strong>Please enter your contact info to create a quote</strong></div></tr>
<tr><td></td></tr>
<tr>
<td><strong>First Name:</strong></td>
<td><input type="text" id="fname" value="Joe"/></td>
</tr>
<tr>
<td><strong>Last Name:</strong></td>
<td><input type="text" id="lname" value="Johnson"/></td>
</tr>
<tr>
<td><strong>Email:</strong></td>
<td><input type="text" id="email" value="joe#johnson.com"/></td>
</tr>
<tr>
<td><strong>Phone Number:</strong></td>
<td><input type="text" id="phone" size="15" value="555-1212"/></td>
</tr>
<tr>
<td><input id="contact_info" type="submit" value="Set My Contact Info" onClick="get_contact_info()" /></td>
</tr>
</tbody>
</table>
</form>
Am I implementing this incorretly?
I am attempting to teach myself basic javascript but I seem to be failing on this piece and don't see where.
Using Firebug in Firefox v30.0, a console call to
document.getElementsByName('fname').value;
returns "undefined"
document.getElementsByName('fname');
returns a NodeList, but no elements.
sigh

Use getelementbyidID not name, or set the name attribute.
contact_info[0] = document.getElementByID('fname').value;

You are using getElementsByName instead of getElementById which will not work given that you never provided any name attributes for the inputs
contact_info[0] = document.getElementById('fname').value;
contact_info[1] = document.getElementById('lname').value;
contact_info[2] = document.getElementById('email').value;
contact_info[3] = document.getElementById('phone').value;

The code you posted has syntax errors, and the part that seems to be throwing an error is commented out. As others have said, you have a problem with getElementsByName and getElementById. But your issues go further than that.
A form can be submitted without clicking the submit button, so it's usual to attach listeners that should run when the form is submitted to the form's submit handler. It also helps to pass a reference to the form using this (the reason will become clear later):
<form onsubmit="get_contact_info(this)" ...>
Form controls are only submitted if they have a name, giving them an ID is usually unnecessary, so change the IDs to names:
<td><input type="text" name="fname" value="Joe"></td>
And the submit button becomes:
<input type="submit" value="Set My Contact Info">
Now you also have a very convenient way to access the form controls using their name as properties of the form. Since a reference to the form was passed in the call (see above), the function can be:
var contact_info = [];
function get_contact_info(form) {
contact_info[0] = form.fname.value;
contact_info[1] = form.lname.value;
contact_info[2] = form.email.value;
contact_info[3] = form.phone.value;
alert("Name = " + contact_info[0] + " " + contact_info[1]);
alert("Email = " + contact_info[2] + ", Phone Number " + contact_info[3]);
}
Also note that getElementsByName returns a live NodeList that doesn't have a value property, so if you were going to use it, you'd use it like:
document.getElementsByName('email')[0].value
You could also create the array using an array literal:
contact_info = [form.fname.value, form.lname.value, form.email.value, form.phone.value];

Related

Addition of Textbox Values which having same name & id ( Textbox getting for loop as per database )

Good Afternoon... I am trying to do the addition of textbox value and show in total textbox using onBlur but not able to do the same. Textbox are generated using foreach loop as per buffaloID base on database which having same name and id. ( Ref. Attached Image) For first textbox, the function gives the value but for next textboxes, not able to get the same.
My Modal Table Code.
#foreach ($buffalodata as $item )
<tr>
<td>{{$item->buffaloID}}</td>
<td><input type="number" id="eachmorningmilk" name="eachmorningmilk" value="00"></td>
<td><input type="number" id="eacheveningmilk" name="eacheveningmilk" value="00"></td>
<td><input type="text" id="eachtotalmilk" name="eachtotalmilk" value="00" readonly></td>
</tr>
#endforeach
JavaScript Code for Function to run onblur
$("#eachmorningmilk").blur(function(){
eachbmorning = parseInt($("#addmilkbuffalo #eachmorningmilk").val());
eachbevening = parseInt($("#addmilkbuffalo #eacheveningmilk").val());
var eachbuffalototalmilk = eachbmorning + eachbevening;
document.getElementById('eachtotalmilk').value=eachbuffalototalmilk;
})
Ref. Images
Please use the onchange method and assign unique id and name to each field. You can refer to the below code and it will work.
HTML
<tr>
<td>{{$item->buffaloID}}</td>
<td><input type="number" id="eachmorningmilk{{$item->buffaloID}}" name="eachmorningmilk{{$item->buffaloID}}" onchange="totalmilk({{$item->buffaloID}})" value="00"></td>
<td><input type="number" id="eacheveningmilk{{$item->buffaloID}}" onchange="totalmilk({{$item->buffaloID}})" name="eacheveningmilk{{$item->buffaloID}}" value="00"></td>
<td><input type="text" id="eachtotalmilk{{$item->buffaloID}}" name="eachtotalmilk{{$item->buffaloID}}" value="00" readonly></td>
JS
function totalmilk(id){
var morningmilk = "#eachmorningmilk"+id;
var eveningmilk = "#eacheveningmilk"+id;
var totalmilk = "eachtotalmilk"+id;
eachbmorning = parseInt($(morningmilk).val());
eachbevening = parseInt($(eveningmilk).val());
var eachbuffalototalmilk = eachbmorning + eachbevening;
document.getElementById(totalmilk).value=eachbuffalototalmilk;
}

User input to build URL

I have a bit of experience with HTML but am very new to JavaScript. In essence, I would like for a user input to be part of a URL. For example, we could have something simple such as:
<script>
function get_cityname() {
var cityname = document.getElementById("cn").value;
alert(cityname);
}
</script>
<form>
Enter city name:
<input type = "text" size = "12" id = "cn">
<input type = "submit" onclick = "get_cityname();">
</form>
This will create a textbox where a user inputs their text (city name) and then click the 'submit' button next to it, and an alert should pop up based on the information they provided, just to make sure this works. However, this code only would seem to work (because of the 'onclick' command) to work for one user input. Therefore, I have 2 questions:
How could the above variable be included in a URL string? If it were something simple as:
URLstring = "https://sampleurl" + cityname + "moretext.html"
How could this be expanded if I want to include two or possibly even n number of inputs? For example, if I create more user prompt boxes and want to have the user also be able to input their zipcode, or state abbreviation, for example:
URLstring = "https://sampleurl" + cityname + "moretext" + zipcode + "moretext" + "stateabbreviation.html"
You could do something along these lines (it would be the same for one or more fields):
// Ensures the DOM (html) is loaded before trying to use the elements
window.addEventListener('DOMContentLoaded', function() {
var cnInput = document.getElementById("cn"),
zipInput = document.getElementById("zip"),
form = document.getElementById("myForm");
form.addEventListener('submit', getUrl); // On submit btn click, or pressing Enter
function getUrl(e) {
var cityname = cnInput.value,
zipcode = zipInput.value,
url = "https://sample.com/" + cityname + "/" + zipcode + ".html";
alert(url);
e.preventDefault(); // Prevent the form from redirecting?
}
});
<form id="myForm">
<label>Enter city name: <input type="text" size="12" id="cn"></label>
<label>Enter zip code: <input type="text" size="12" id="zip"></label>
<input type="submit">
</form>
First specify an action attribute for your form. This is where your form will be submitted. Then set your form's method attribute to GET. Finally, add as many fields as you like (I am assuming you are after a GET query such as https:url.com?key1=val1&key2=val2...):
<form method="GET" action="https://sampleurl">
Enter city name:
<input type="text" size="12" id="cn">
Enter zip code:
<input type="text" pattern="[0-9]{5}"
<input type="submit" ">
</form>

Why is the data being displayed many times over the loop?

I have been trying to set up a kind of search engine connected to an API. It takes the user input and gives back the information from the API. In the future there should be a "dynamic" amount of input fields but for the moment I am working with a fixed amount of five. The loop takes the amount of fields and calls the API that amount of times with that input.
I tried placing a constant (i.e. 5) in the loop but still, the funny part is that with 3 it of course calls the app three times but outputs 6 fields, and with 2 it calls the API 2 times but outputs three rows so it seems that it does not obey the loop but something else. Meanwhile in the console (with log) I can see that the API is properly called only the times defined by the loop so I believe something goes wrong at the $.getJSON level
The problem is at the end a table is created with 15 rows instead of the expected 5 (one row for every input). Why do you think this is happening?
Thanks in advance
<form name="inputform" method="get" width="50">
<input type="text" name="field0" id="field0" size="50">
<input type="text" name="field1" id="field1" size="50">
<input type="text" name="field2" id="field2" size="50">
<input type="text" name="field3" id="field3" size="50">
<input type="text" name="field4" id="field4" size="50">
</form>
<table id="table">
<tr>
<th>id</th>
<th>Name</th>
<th>Age</th>
<th>Preference</th>
</tr>
</table>
<input id="getInfo" type="button" value="Submit" /><br/>
var customURL = "http://apitest.com/test/";
var customURL1 = '';
$('#getInfo').click(function() {
$('#table tr').not(':first').remove();
var fields = document.getElementsByTagName('input');
var table = document.getElementById('table');
if (localStorage.myJSON !== undefined) {
var myJSON = JSON.parse(localStorage.myJSON);
}
var html = '';
for (var i = 0; i < elements.length - 1; i++) {
customURL1 = customURL + document.getElementById('field' + i + '').value;
console.log(customURL1);
$.getJSON(customURL1, function(data) {
console.log(data);
html += '<tr><td>' + data.sample_list.id + '</td><td>' + data.sample_list.name + '</td><td>' + data.sample_list.age + '</td><td>' + data.sample_list.preference + '</td></tr>';
$('#table tr').first().after(html);
Each time you get an AJAX response, you're appending the response to the html variable, and then adding that after the first row of the table. Since the html variable already contains the results from the previous responses, and they were insert into the table already, you get duplicates.
Instead of concatenating the new row to html, just insert the new row directly into the table.
$.getJSON(customURL1, function(data) {
console.log(data);
$('#table tr').first().after('<tr><td>' + data.sample_list.id + '</td><td>' + data.sample_list.name + '</td><td>' + data.sample_list.age + '</td><td>' + data.sample_list.preference + '</td></tr>');

Error "undefined is not a funcion" when performing a $.find

guys,
once again I come begging for help. I can't get my head around this - all I need is update the name attribute's indexes of texts in my form. I want to show to the user one line in the table and, as he/she clicks on the plus sign, another line is added.
For my form to work on the server side, I need do reindex the name parameter. That's how I'm trying to do it:
function reindex () {
$("table").find("tr.faixa").each(function(index, value) {
value.find("input.faixa_min").attr("name", "data[" + index + "][BonusRecarga][faixa_min]"); // <- here's where I get the error
value.find("input.faixa_max").attr("name", "data[" + index + "][BonusRecarga][faixa_max]");
value.find("input.valor_bonus").attr("name", "data[" + index + "][BonusRecarga][valor_bonus]");
value.find("input.perc_bonus").attr("name", "data[" + index + "][BonusRecarga][perc_bonus]");
});
}
And here's a fragment of the form:
<tr class="faixa">
<td>
<input name="data[0][BonusRecarga][faixa_min]" class="faixa_min" type="text" required="required"/>
</td>
<td>
<input name="data[0][BonusRecarga][faixa_max]" class="faixa_max" type="text" required="required"/>
</td>
<td>
<input name="data[0][BonusRecarga][valor_bonus]" class="valor_bonus" type="text" required="required"/>
</td>
<td>
<input name="data[0][BonusRecarga][perc_bonus]" class="perc_bonus input-small" type="text" required="required"/>
</td>
<td>
<span class="help-inline"><i class="icon-plus" style="cursor: pointer"></i></span>
<span class="help-inline"><i class="icon-minus" style="cursor: pointer"></i></span>
</td>
</tr>
I have also tried using a common for(var i = 0; i < $(".faixa").lenght; i++), but I always get the "undefined is not a function" in the first value.find(...). It looks like "value" doesn't have the find() method, but when I log it, it shows me a regular "....
Do you know why the find() method is not working on the "value" variable?
Thanks in advance.
value is a DOM Element object while .find() is a jQuery method. You need to create a jquery object :
var $value = $(value);
//Then use $value.find()
Try using $(this).find('input...')... . it works, and is better inside each.
A much faster result for jquery would be to use the EQ function and append.
https://api.jquery.com/eq/
if EQ is not what your looking for leave a comment and ill look further into your issue.

how do i get the info from a form using javascript?

i have a form which user enters some data, could be checkboxes, radio buttons, textfields, etc
when user click submit button, i want to refresh the page with whatever data that was entered
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
</head>
<body id="ref">
<form>
Please enter your name:<input type="text" id="name" />
Please enter your age:<input type="text" id="age" />
</form>
<input type="button" onclick="c()" value="submit">
<script type="text/javascript">
function c()
{
var o = document.getElementById('ref');
o.innerHTML = '';
var n = document.createElement('p');
var nam = document.getElementById('name');
n.innerHTML = "Your name is: " + nam;
o.appendChild(n);
var a = document.createElement('p');
var ag = document.getElementById('age');
a.innerHTML = "Your age is: " + ag;
o.appendChild(a);
//how do i get the info from the form? because both nam and ag are coming up null
}
</script>
</body>
</html>
my guess this is not working is because the page refreshes then tries to fetch the element by id which is not there anymore.. whats the correct way of doing this??
You're confusing objects with their properties. Here, you're getting the HTMLInputElement instance for the "age" field:
var ag = document.getElementById('age');
But here you're using that object as though it were a simple value:
a.innerHTML = "Your age is: " + ag;
The HTMLInputElement object has a value field you can use for that:
a.innerHTML = "Your age is: " + ag.value;
Separately, you're completely destroying the page by doing this:
var o = document.getElementById('ref');
o.innerHTML = '';
...because you've given the body element the ID "ref". Completely replacing the body element completely replaces the body element, so you can't rely on objects that only exist as subordinates of that element.
The usual thing is to have an element to fill in, and (optionally) to remove the elements you no longer need. For instance (live copy):
HTML:
<form id="theForm">
Please enter your name:<input type="text" id="name" />
Please enter your age:<input type="text" id="age" />
<input type="button" onclick="c()" value="submit">
</form>
<div id="result">
</div>
(Note I moved the button into the form for convenience.)
JavaScript:
function c() {
var form = document.getElementById("theForm"),
nameField = document.getElementById("name"),
ageField = document.getElementById("age"),
result = document.getElementById("result");
form.parentNode.removeChild(form);
result.innerHTML =
"Your name is " + nameField.value +
" and your age is " + ageField.value;
}
There, when the button is pressed, I remove the form and fill in the "result" div.
You could add the "result" div dynamically if you wanted (live copy):
HTML:
<form id="theForm">
Please enter your name:<input type="text" id="name" />
Please enter your age:<input type="text" id="age" />
<input type="button" onclick="c()" value="submit">
</form>
JavaScript:
function c() {
var form = document.getElementById("theForm"),
nameField = document.getElementById("name"),
ageField = document.getElementById("age"),
result;
result = document.createElement("div");
result.innerHTML =
"Your name is " + nameField.value +
" and your age is " + ageField.value;
form.parentNode.insertBefore(result, form);
form.parentNode.removeChild(form);
}
You can access the fields using a briefer and somewhat more natural syntax if you change your id values to name values instead (live copy):
HTML:
<form name="theForm">
Please enter your name:<input type="text" name="name" />
Please enter your age:<input type="text" name="age" />
<input type="button" onclick="c()" value="submit">
</form>
JavaScript:
function c() {
var form = document.theForm,
nameField = form.name,
ageField = form.age,
result;
result = document.createElement("div");
result.innerHTML =
"Your name is " + nameField.value +
" and your age is " + ageField.value;
form.parentNode.insertBefore(result, form);
form.parentNode.removeChild(form);
}
Further reading:
DOM2 Core (well-supported by most modern browsers)
DOM2 HTML
DOM3 Core (increasingly supported)
If you want to update your html using java-script only , you may use ".value" attribute of the input;
var a = document.createElement('p').value;
var ag = document.getElementById('age').value;
Usually the Form information is processed using server-side code , this is done by specifying the action attribute of the form:
<form action="processuserinfo.aspx">
...
</form>
I'm pretty sure this isn't doable javascript alone. You'll need to use a server-side language like php. Try to google php forms, and you should get some good results. :)

Categories