Javascript and radio buttons - Not doing anything - javascript

This one is bound to be simple (I hope) something I am overlooking. I have a set of 50 questions that are asked pulled from a table and put into a form for answering. I want to check to make sure they have all been answered (required). When the user hits submit, none of the alert boxes (even the debugging boxes) appear. What am I dong wrong here?
First, the PHP:
echo 'Please complete ALL 50 questions, then press the "SUBMIT" button at the bottom of the page.';
$query = "SELECT *
FROM `starriskquestions`
ORDER BY `QuestionNum` ASC";
$results = $pdo->query($query);
echo '<form name="submitra" action="riskassessmenttest.php" onsubmit="return validateForm()" method="post">';
while ($row = $results->fetch()) {
echo '<br>' .$row["QuestionNum"] . ') ' . $row["Question"] . '<br>
<input type="radio" name="a'.$row["QuestionNum"].'" value="1" /> Yes ----
<input type="radio" name="a'.$row["QuestionNum"].'" value="-1" /> No<br><br>';
}
echo "<br> ARE YOU SURE YOU ANSWERED ALL 50 QUESTIONS??? <br> If so, click the ";
echo "submit buton below <br>";
echo '<input type="hidden" name="testid" value="'.$testid.'">';
echo '<input type="submit" name="submittestanswers" value="submit">';
echo ' </form>';
Then the Javascript
function validateForm()
{
for (var answerloop=1; <=50; answerloop++)
{
var answernum = '"'+ "a" + answerloop + '"';
alert (answerloop);
var x=document.getElementByName(answernum).value;
alert ("This is the variable X: " + x);
if (x!=="1" || x!=="-1")
{
alert(" One or more questions must be filled out");
return false;
}
}
}

1, incorrect second argument in for loop
2, document.getElementByName() should be document.getElementsByName()
function validateForm(){
for (var answerloop=1; answerloop<=50; answerloop++){
var name = 'a' + answerloop;
var names=document.getElementsByName(name);
var is_checked = false;
for(var i=0;i<names.length;i++){
if(names[i].checked){
is_checked = true;
}
}
if(!is_checked){
alert("One or more questions must be filled out");
return false;
}
}
}
tested by:
<form onsubmit="return validateForm()" method="post" action="./">
<?php
for($x=1;$x<=50;$x++){
echo <<<EOD
<input type="radio" name="a{$x}" value="1">
<input type="radio" name="a{$x}" value="-1">
EOD;
}?>
<input type="submit" value="submit">
</form>

I think this is wrong:
for (var answerloop=1; <=50; answerloop++)
Change it to this:
for (var answerloop=1; answerloop <=50; answerloop++)

Your for loop is missing answerloop in the second param
for (var answerloop=1; <=50; answerloop++)
^
change to
for (var answerloop=1; answerloop<=50; answerloop++)

Related

Value from textbox gets blank after update

I have this edit link (name) where the value from the database gets transformed to textbox when clicked. The problem is when I update other normal textbox (age), the value from the edit link textbox becomes blank. But when I input a value into the edit link textbox, the value is saved. Why is it that everytime I update other textbox, the edit link textbox value becomes blank? Please help
$(document).ready(function() {
$('a.edit').click(function (e) {
e.preventDefault();
var dad = $(this).parent().parent();
dad.find('label').hide();
dad.find('input[type="text"]').show().focus();
return false;
});
$(".edit-input").focusout(function() {
var dad = $(this).parent();
$(this).hide();
dad.find('label').show();
});
$sql = "SELECT * FROM details";
$result = mysqli_query($conn,$sql);
while ($rowwaf = mysqli_fetch_assoc($result)) {
echo "<td><label for=\ "name\" class=\ "control-label\">
<p class=\"text-info\" style=\"color: black\">".$rowwaf["name"]."</p></label>
<input type=\ "text\" class=\ "edit-input\" name=\ "name\" placeholder=\ " ".$rowwaf[ "name"]. " \" maxlength=\ "10\" />
<div class=\ "controls\">
<a class=\ "edit\" href=\ "#\">Edit</a>
</div>
echo "<td ><input size=\"18\" type=\"text\" name=\"age\" value=\"".$rowwaf["age"]."\"></td>\n" ;
</td>";
My update query:
$name = $_POST["name"];
$age = $_POST["age"];
$id = $_POST["id"];
$updquery = "UPDATE details
SET name = '$name', age = '$age'
WHERE id = '$id'";
$result = mysqli_query($conn,$updquery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I guess the problem is with the echo statement from php.
<input type="text" class="edit-input" name="name" placeholder="$rowwaf["name"]" value="$rowwaf["name"]" maxlength="10" />
You are setting placeholder, I guess you also need to set the value attribute to the input tag.
If it doesn't help, try including a running snippet. Maybe we could do something about it then!

Posting JavaScript Variable to MySQL using PHP

I am trying to send a JavaScript variable to PHP but not exactly sure how to do it, a few things have said Ajax but I've never used it before and can't get my head around it. Does anyone know what the easiest way to do this would be? The column which I am attempting to populate in my DB is called 'cogs'.
I have the following JavaScript code:
<script>
$(document).ready(function() {
$('#duration-select').change(function() {
var cogs = $('#cogsday').html();
cogs = cogs.replace(/\D/g,'');
var x =$('#duration-select').val();
var y = cogs * x;
$('#request').removeClass('hidden');
$('#duration-value').text('Total cost for this duration = ' + (y) + ' cogs');
if($(this).val() !== '') {
} else {
$('#duration-value').text('');
}
});
$('#request').click(function() {
var cogs = $('#cogsday').html();
cogs = cogs.replace(/\D/g,'');
var x =$('#duration-select').val();
var y = cogs * x;
$('#total').text(y);
});
});
</script>
And the following HTML code:
<label id="total"></label>
Here is where I am trying to post the data, everything else is posting except for the $cost:
<form name="form" method="post">
<div class="modal-footer">
<?php
if ($row3['availability'] === 'Available') {
if (isset($_POST['request'])) {
$to_id = $row3['customerid'];
$from_id = $_SESSION['customerid'];
$time_sent = date('Y-m-d H:i:s');
$subject = 'Request for ' . $row3['title'];
$title = $row3['title'];
$listingid = $listingid;
$cost = $_POST['total']; //posting 0
$message = $customer_data['first_name'] . ' ' . $customer_data['last_name']
$request = mysql_query("INSERT INTO messages (to_id, from_id, listing_id, time_sent, subject, message, cogs, messagenumber, title, msgrand) VALUES ('$to_id', '$from_id', '$listingid', '$time_sent', '$subject', '$message', '$cost', '1', '$title', '$randomString')") or die(mysql_error());
}
}
?>
<input type="submit" class="btn btn-success" name="request" value="Yes" />
<input type="submit" class="btn btn-danger" data-dismiss="modal" value="No" />
</div>
</form>
Then I am trying to post the value of the label id=total to my db or the JavaScript variable (y). The problem is that 0 is always being sent to the DB when it should instead be the value that is in the label where the id is total.
Use name parameter for hidden variable and it will be automatically passed to PHP .
<label id="total"></label>
<input type="hidden" name="total" id="nameID"/>
in javascript below $('#total').text(y); write $('#nameID').val(y); . Everything will work properly.
You used total label , but $_POST recognizes only input type so use input type=.... instead of a label,divs etc.
IF YOU REAllY NEED ANSWER REPLY HERE
you have make an input type and its value is to be set by that javascript and then you'll be able to get that $cost value in php code
<input type="hidden" value="" name="total" id="total">
..................
$("#total").val(y);
You can use this to send the variables....
<input type="text" id="name" class="name" placevalue="Enter you name" required /><br><br>
<input type="text" id="email" class="email" placevalue="Enter you name" required /><br><br>
<button id= "det_submit" onclick="submit_det()"> Submit </button>
<script>
function submit_det() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if(name != "" && email != "") {
$.post(
'xx.php',
{
name : document.getElementById("name").value,
email1 : document.getElementById("email").value,
},
function(data){
alert(data);
});
} else {
alert("empty");
}
}
</script>
here is xx.php
<?php
if(isset($_POST['name']) && isset($_POST['email1'])) {
$name = $_POST['name'];
$email = $_POST['email1'];
//code to insert into your database......
}
?>
Use a ID and Name for hidden parameter like this
<label id="total"></label
<input type="hidden" name="name" id="name"/>
and in jQuery edit the code like this
$('#total').text(y);
$('#nameID').val(y);
hope that it will work

Disable button with checkbox in table

I have an array of data on which each row has a checkbox which the user can check to select a row.
I want to make it so that if no row is selected, the "delete" button will be disabled.
The button gets disabled on page load, and the checkbox on row 1 works as planned, but if the table contains 2 or more rows the rest don't.
This is what I have so far:
<button class="btn btn-default modal-opener" id="chkboxdelbtn" onchange="toggle();" type="button" type="submit">Delete Selection</button>
<?php
$row = get_member_tskey_info($mysqli);
$i = 0;
foreach ($row as $r){
echo '<tr><td style="padding-right:0px;">';
if (($i<=2) && ($r['status'] == 1)){
echo '<input type="checkbox" name="keyselect[]" id="keyselect[]" value="' . $r['uid'] . '" /></td>';
}else{
echo '<input type="checkbox" disabled="disabled" value="" /></td>';
}
...
Javascript:
document.getElementById('chkboxdelbtn').disabled = true;
function toggle() {
if (document.getElementById('keyselect[]').checked == true) {
document.getElementById('chkboxdelbtn').disabled = false;
} else {
document.getElementById('chkboxdelbtn').disabled = true;
}
}
IDs have to be unique. Use a class instead.
foreach ($row as $r){
echo '<tr><td style="padding-right:0px;">';
if (($i<=2) && ($r['status'] == 1)){
echo '<input type="checkbox" name="keyselect[]" class="keyselect" value="' . $r['uid'] . '" /></td>';
}else{
echo '<input type="checkbox" disabled="disabled" value="" /></td>';
}
Javascript:
document.getElementsById('chkboxdelbtn').disabled = true;
function toggle(){
var keyselects = document.getElementsByClassName('keyselect');
for (var i = 0; i < keyselects.length; i++) {
if (keyselects[i].checked == true) {
document.getElementById('chkboxdelbtn').disabled = false;
break;
}
}
}
Be aware for the duplicate ID's on your checkbox. It cannot happen. Actually, you wouldn't even need an id to the checkbox, as you can make your toggle() function much simpler with querySelectorAll():
function toggle() {
document.getElementById('chkboxdelbtn').disabled =
( document.querySelectorAll("input[type='checkbox']:checked").length <= 0 );
}
This will look for all input checkboxes that are checked, and see if there's at least one. If not, it get's disabled.
https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll

document.getElementById injecting Answer from prompt in to wrong place

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>

Validating check box and input

i have a form that includes several text inputs and checkboxes (the checkboxes comes from a DB), so... i know how to validate them separetly but i need to validate them together, the way i'm doing this only validate checkboxes, i know why its happening but i don't know how to write the right way... ¿can you help me? here is the code:
<form action="sendreq.php" name="contact" onsubmit="return valida_frm(this)" method="post">
<label>Name</label>
<input name="name" type="text" />
<label>Email</label>
<input name="email" type="text"/><!-- And Severeal inputs then the checkboxes-->
<?php $list3 = mysql_query("SELECT * FROM products ORDER BY id ASC LIMIT 20");
while($row = mysql_fetch_object($list3)){ ?>
<input id="product" name="product[]" class="label" type="checkbox" value="<?php echo $row->name?>"><label class="label"><?php echo $row->name?></label>
<?php }?>
The Validation doesn't work fine its evident why, i just need the right way to write and unify the return of the alert:
function valida_frm(form){
var alerta="Ooops:\n";
if (form.name.value == "") {alerta+="Name.\n";}
if (form.email.value == "") {alerta+="Email.\n";}
for(var i = 0; i < form.product.length; i++){
if(form.product[i].checked)return true;}
alert('Oooops');
return false;
if (alerta!="Error:\n"){
alert(alerta);
return false;
}else{
return true;
}
}
Thanks for your time!
Do not call a field for "name" and then test form.name since it already has a .name
Then test form["product[]"] and not form.product - you cannot have id="product" since ID has to be unique!
I suggest you give id="product<?echo $somecounter; ?>" />...<label for="product<? echo $somecounter; ?>">...</label>
Also test against Error (or nothing as in my suggesion) and not Oops
Also more issues fixed
DEMO
function valida_frm(form){
var alerta="";
if (form.name.value == "") {alerta+="Name.\n";} // Please use FullName or such
if (form.email.value == "") {alerta+="Email.\n";}
var chks = form["product[]"],
checked = false;
for(var i = 0; i < chks.length; i++) {
if(chks[i].checked) {
checked = true;
break;
}
}
if (!checked) {
alerta+='Product.\n';
}
if (alerta){
alert("Error:\n"+alerta);
return false;
}
return true;
}

Categories

Resources