document.getElementById injecting Answer from prompt in to wrong place - javascript

A while ago I found a function (on here) that would allow me to launch a Javascript prompt box on form submit, it would take a value and then submit it alongside the submitted form.
I've been racking my brain as to why this isn't working correctly. At the moment, if I click submit on the form on a row that isn't the very first row in my table, it submits the form on the first row.
The function uses document.getElementById to find where it's entering the entered text but because it's a while loop, document.getElementById("invoiceEntry").value = answer; exists on every row of the table and it injects the text in to the very first instance.
Is there an easy solution to this?
Here's a snippet of my code:
<script language="Javascript">
function invoiceCollect() {
var answer = prompt("Enter invoice number:");
if(answer) { // answer = false if "cancel" pressed.
document.getElementById("invoiceEntry").value = answer;
return true;
}
else if(answer == "") { // return false if no input entered, i.e. ""
return false;
}
else
return false;
}
</script>
<form id='invoice' method='post' action='update_item.php' onsubmit='return invoiceCollect()'>
<input type='hidden' name='invoiced' >
<input type='hidden' name='id' value='" . $row['id'] . "' >
<input type='hidden' name='invoiceNo' id='invoiceEntry' value='' >
</form>
<input type='submit' value='Invoice' form='invoice'>

I will assume that the while loop you're talking about is server side, in PHP and it wraps the HTML you posted. If that is not the case, please comment and i will delete the answer as it would be off-topic.
Problem 1:
Your function shouldn't be defined in a loop. You want all your functions to do the same thing, maybe to a different element. A single function with the element as a parameter would be all that's needed.
Problem 2:
Identifying the correct element. This is the actual problem you're facing. All your functions use the first element with that ID because that's just how HTML is defined, it expects the IDs to be unique.
The simplest solution is to add the form as parameter to the function:
JavaScript:
function invoiceCollect(form) {
form.invoiceNo.value = 'WORKS';
}
HTML:
<form onsubmit = 'return invoiceCollect(this)'>
DEMO

Make the
<input type='submit' value='Invoice' form='invoice'>
before the
</form>
so it would be like this :
<script language="Javascript">
function invoiceCollect() {
var answer = prompt("Enter invoice number:");
if(answer) { // answer = false if "cancel" pressed.
document.getElementById("invoiceEntry").value = answer;
return true;
}
else if(answer == "") { // return false if no input entered, i.e. ""
return false;
}
else
return false;
}
</script>
<form id='invoice' method='post' action='update_item.php' onsubmit='return invoiceCollect()'>
<input type='hidden' name='invoiced' >
<input type='hidden' name='id' value='" . $row['id'] . "' >
<input type='hidden' name='invoiceNo' id='invoiceEntry' value='' >
<input type='submit' value='Invoice' form='invoice'>
</form>

Related

JavaScript not running correctly from HTML form

I'm creating a web front for a database using HTML, CSS, JavaScript and PHP for my uni coursework. I've only got so far as HTML and JavaScript form validation before I've run into this weird problem.
In my HTML, I link the JavaScript as follows:
<script type="text/javascript" src="dbicw2.js"></script>
Correct file name, I've checked.
Next, I have a form which takes a user's search. It upon submitting runs my JavaScript function, and its action is a PHP file. The code is as follows:
<form action="dbicw2.php" onSubmit="return validate(this)">
<input type="text" name="title">
<input type="submit" value="submit">
</form>
Again, correct PHP filename and JS function name.
Now, my JavaScript function seems to always return True, regardless of what happens. Currently, my JS looks like:
function validate(form)
{
alert("Hi")
for (var field in form.elements) { //For elements in form
field+="" //Incase it is undefined
alert("This element: '" + field.value + "'")
if (field.value.trim() == "") { //If the string is empty
alert(field.name + " is empty.") //Alert message
return false //Failed validation
}
}
return true //Otherwise, successful validation
}
Not even the alert message at the top runs. The form just goes through and PHP is loaded, regardless of the JS. The script neither works in Edge.
This is baffling because my code is a near clone of my professor's example, which works.
What is causing the Javascript to not be run and the PHP action done?
Edit: my professor's example code, which works:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>(prof name)</title>
<LINK REL='stylesheet' TYPE='text/css' HREF='dbicw.css'>
<script type="text/javascript" src="dbicw.js"></script>
</head>
<body>
<h1>Search for a Movie by Title</h1>
<form action="search_movie_example.php" onSubmit="return validate(this)">
Movie title:<br>
<input type="text" name="title">
<br>
<br>
<input type="submit" value="Search">
</form>
</body>
</html>
JavaScript:
function validate(form)
{
var ok=1
var msg=""
for (var i = 0; i < form.length; i++) {
if (form.elements[i].value.trim() == "") {
msg += "'" + form.elements[i].name + "' is void. "
ok=0
}
}
if (ok == 0) {
alert(msg)
return false
}
else {
return true
}
}
I think I found a mistake (hopefully THE mistake) in your code. It's really simple, but very common.
You iterate over your form elements using for (var field in form.elements), but this will iterate over the index values of the form elements, rather than over the actual elements. Change in to of to iterate over the actual values instead.
Example:
let arr = ['foo', 'bar', 'cat'];
for (let word in arr) {
console.log(word); // prints 0, 1, 2
}
for (let word of arr) {
console.log(word); // prints foo, bar, cat
}
Try this:
function validate(form) {
event.preventDefault();
alert("Hi")
for (var field of [...form.querySelectorAll('input:not([type="submit"])')]) { //For elements in form
alert("This element: '" + field.value + "'")
if (field.value.trim() == "") { //If the string is empty
alert(field.name + " is empty.") //Alert message
}
}
}
<form action="dbicw2.php" onsubmit="validate(this)">
<input type="text" name="title">
<input type="submit" value="submit">
</form>
I added an event.preventDefault() so the page wouldn't be redirected in the live example, and changed the in to of while also altering the statement that "fetches" the input elements. The of simply allows you to iterate through the array, and the actual selector just gets all the input elements that are not of the type submit.
If you only want to alter your code to make it work, then try this:
function validate(form) {
alert("Hi")
for (var field of [...form.elements]) { //For elements in form
alert("This element: '" + field.value + "'")
if (field.value.trim() == "") { //If the string is empty
alert(field.name + " is empty.") //Alert message
return false //Failed validation
}
}
return true //Otherwise, successful validation
}
<form action="dbicw2.php" onSubmit="return validate(this)">
<input type="text" name="title">
<input type="submit" value="submit">
</form>
I again changed the in to of, and added a spread operator to convert the HTMLFormControlsCollection to an array.

How to insert the value of dynamically radio button using PHP?

I have a html table, each table row have a radio button dynamically generated. Each option in the radio button have a unique id that generated dynamically also. But this id is not yet save in the database.
How to insert the option id? And how to update the option answer in that option id? Please help me. I tried to insert the values but I have no luck
Scenario:
There's a default value for the radio button, which is "No". When the user change the default value, there's a confirmation box that will ask the user if he/she want to processed. If the user click "Ok" the default value will change into "Yes".
PHP for html table:
echo '<td id="resumeFile'.$optionId.'">' . $record_s->attachment_resume_id . '</td>';
echo '<td id="processedYes><label for="Yes">Yes</label>
<input type="radio" id="processedOptionYes'.$optionId.'" name="processedOption" value="Yes" onclick="proccessedCheck('.$optionId.',\'Yes\')"/>
<label for="No">No</label>
<input type="radio" id="processedOptionNo'.$optionId.'" name="processedOption" value="No" checked="checked" onclick="proccessedCheck('.$optionId.',\'No\')" echo $record_s->process_resume === "No" checked="checked"/>/>No</td>';
echo '</tr>';
}
echo '</table>';
}
if (isset($_POST['optionId']) && $_POST['optionId']){
$optionId = $_POST['optionId'];
$queryOptionId = $wpdb->query("INSERT INTO resume_databank(process_resume_id) VALUES ('$optionId')");
}
Hidden Form:
<form id='hiddenForm' method='POST' action=''>
<input type="hidden" id="inputHidden1" name="optionId" />
<input type="hidden" id="inputHidden2" name="optionAnswer" />
</form>
JS:
function proccessedCheck(optionId,optionAnswer){
if(optionAnswer == 'Yes'){
if (confirm('You have chosen ' + optionAnswer + ', is this correct?')){
jQuery("#processedOptionYes" + optionId).attr('disabled',true);
jQuery("#processedOptionNo" + optionId).attr('disabled',true);
var withlink = jQuery("#resumeFile"+ optionId).html();
var withoutlink = jQuery(withlink).html();
jQuery("#resumeFile"+optionId).html("").append(withoutlink);
jQuery("#inputHidden1").val(optionId);
jQuery("#inputHidden2").val(optionAnswer);
jQuery("#hiddenForm").submit();
}
}
}
Hi u can change the jquery by using like below with using a class instead of function in the input type, add a class radiods to input type= radio.
$(".radiods").click(function(){
var clickid = this.id;
if($('input:radio[name=processedOption]:checked').val() == "Yes")
{
if (confirm('You have chosen YES, is this correct?'))
{
$("#inputHidden1").val(clickid);
$("#inputHidden2").val("Yes");
}
}
});
and then use ajax to update in database,so no need of form
I dont use Jquery, but Javascript is pretty simple to read the value. It is the same as a checkbox value in that it is .checked when true.
Loop through your form fields looking for checked items
var formObj = document.getElementById('hiddenform');
for(var i = 0;i < formObj.elements.length;i++){
radiovalues[] = escape(formObj.elements[id].checked);
}
Most fields have a value, ie text, hidden, password etc
escape(formObj.elements[id].value)
The checkbox and radio doesnt have a value, you are looking for "checked" which will return true or false.

Without using a form, how can I check an input field is not empty before running function?

I have the following code in a SharePoint aspx page ( I got an error that said I cannot use form controls... that is why the form tags are not there):
<div id="formBox">
Here is a link : <a href="" id=lnk>nothing here yet</a> <br>
<input type='text' id='userInput' />
<input name="codename" type="radio" value="codeA" /> <label for="x">X</label> <input name="codename" type="radio" value="codeB" /><label for="y">Y</label>
<input type='button' onclick='javascript:changeText2()' value='Change Text'/>
</div>
Here is the function which is supposed to concatenate the information: It works... kind of.. parts of it.
It will add the selected button to the url, and also the input text. However, it is firing before the input is filled out, and then works once you type in the box again.
I tired to add in if statement, to stop the code if the box was not filled out but it didn't work. Here is what I have...
function changeText2(){
var userInput = document.getElementById('userInput').value;
$('#formBox input[type="text"]').on('change', function() {
var linktest = 'site/info.aspx?' + $('input[name="codename"]:checked', '#formBox').val() + '=' + userInput;
alert(linktest);
});
var lnk = document.getElementById('lnk');
lnk.href = "http://www.google.com?q=" + userInput;
lnk.innerHTML = lnk.href;
}
I tried to check the input box like this, but it didn't work:
if( $('#formBox input[type="text"]').val== "") {
alert('no info');
}
It should be val() in jquery, not val. However, it will be value in javascript, not val. Simply just use unique id, try something like this,
For Jquery:
if( $('#userInput').val() === "") {
alert('no info');
}
For javascript:
if(document.getElementById("userInput").value === "") {
alert('no info');
}

How to use if condition in document.getelementbyname in javascript

Here I am facing problem in if condition it validates for subject and not validate for medium field. Here checkbox is coming from mysql. But it gives source like this only. Here Know the problem is with if conditional only how to overcome this?can any figure out what is the problem in my code?what I have to do here.I hope everyone understand the question.I don't understand why the second if conditional statement is not working.
function check() {
//alert('done')
var chk = document.getElementsByName('subject[]');
var reg = document.getElementsByName('regional[]');
var len = chk.length;
var regl = reg.length;
//alert(len);
if (len) {
for (i = 0; i < len; i++) {
if (chk[i].checked) {
return true;
} else {
alert('please select the subject');
return false;
}
}
}
if (regl) {
for (i = 0; i < regl; i++) {
if (reg[i].checked) {
return true;
} else {
alert('please select the regional');
return false;
}
}
}
}
<form name="f1" action="" method="post">
Subject
<input type='checkbox' name='subject[]' value='science'>science<br/>
<input type='checkbox' name='subject[]' value='maths'>maths<br/>
Medium
<input type='checkbox' name='regional[]' value='Hindi'>Hindi<br/>
<input type='checkbox' name='regional[]' value='english'>english<br/>
<input type="submit" name="land" class="butt" value="SUBMIT" onClick="return check();">
</form>
Because if the first condition is getting false then it will stop executing the code because you have "return".
At a time both will not be validate as per you code.
First make all the subject checked and then try, you will get the second if will be working.
function check() {
var subjects = document.getElementsByName("subject[]"),
regionals = document.getElementsByName('regional[]'),
subjectSelected = false,
regionalSelected = false;
// check subject
for(var i=0;i<subjects.length;i++){
if(subjects[i].checked){subjectSelected = true;}
}
// check medium
for(var i=0;i<regionals.length;i++){
if(regionals[i].checked){regionalSelected = true;}
}
if(!subjectSelected || !regionalSelected){
if(!subjectSelected){ // subject not selected
alert("Please select a subject.");
}else{ // medium not selected
alert("Please select a regional.");
}
}
}
<form name="f1" action="" method="post">
Subject
<input type='checkbox' name='subject[]' value='science'>science<br/>
<input type='checkbox' name='subject[]' value='maths'>maths<br/>
Medium
<input type='checkbox' name='regional[]' value='Hindi'>Hindi<br/>
<input type='checkbox' name='regional[]' value='english'>english<br/>
<input type="submit" name="land" class="butt" value="SUBMIT" onClick="return check();">
</form>
the mistake you did very silly. whenever you will use the return key it will exit the function and won't process below or next codes. Moreover, I think you are trying to validate the form like if at least one subject and medium is selected the form is valid. Either you want to alert the user. The easy way to do that is first take two variable inside the function, one for subject another one for medium and set both of them to false, that means nothing is selected. Now run a loop and set the related variable true if the checkbox is checked, that means at least one is checked what you want. After two loops now write a if-else-then condition for below three states:
Both true -> at least one subject and medium is checked
one true, one false -> either subject or medium is not selected.
both false -> nothing selected.
if you are trying something else leave a comment and I will post the solution. besides, feel free to ask if you have further questions.

insert multiple input text at the same name in sql and php

i want to insert multiple input in the same table using php and sql
example:
<script language="javascript">
fields = 0;
function addInput() {
if (fields != 10) {
document.getElementById('text').innerHTML += "<input type='text' name='order'><br/>";
fields += 1;
} else {
document.getElementById('text').innerHTML += "<br />Only 10 insert fields allowed.";
document.form.add.disabled=true;
}
}
</script>
<form action='insert.php' method='post'>
<input type='text' name='order'>
<div id="text">
</div>
<br /><input type='button' value='add new input' onclick='addInput()'> <input type='submit' value='submit'>
</form>
in this code i have unlimited input, i have to insert it in:
dbtable = clients_order
row name : order
++++++++++++++++++
+ id + order +
++++++++++++++++++
so when i use this code :
$order=$_POST['order'];
foreach ($order as $insert_order) {
mysql_query("INSERT INTO clients_order (order)
VALUES ('$insert_order')");
}
Error message : Warning: Invalid argument supplied for foreach()
please help me to do that
thank you
The foreach() is complaining that $order isn't an array. If you use order[] as the name field in the HTML for your field, then PHP will turn them all into an array for you.
You should also check you have an array (use is_array()) before giving it to a foreach() loop. And you should call mysql_real_escape_string() over each piece of text from $orders in order to prevent SQL injection attacks.

Categories

Resources