I have a hidden field. When user click on a button (here delete button) its value is set is as one in java script.Now I want to get its value on posting the input field - submit .
My code is here.
<input type="hidden" name="clicked_delete_btn" id="clicked_delete_btn" value=""/>
<input type="button" name='delete' id='delete' value="Delete" onClick="return confirm_delete(this);">
<input type="submit" name="update" value="UPDATE" >
javascript
function confirm_deleteo(ele) {
if (confirm('Do you wish to delete the file?')) {
ele.style.display = 'none';
document.getElementById('clicked_delete_btn').value = 1;
return true;
} else return false;
}
php code
if(isset($_POST['update'])) {
$delete_clicked=$_POST['clicked_delete_btn'];
if($delete_clicked==1) {
//do operations
}
}
But it's value is not getting on $_POST['update'].
You need to use ID instead of name
document.getElementById('clicked_photo_delete_btn').value = 1;
I have tried to assemble your code and it works fine on my system:
http://pastebin.com/NAEYAZre, http://pastebin.com/3vEsrHJJ
Check your form tag options.
Related
I have the following issue:
I have a foreach within a form, within this form I have a number type input that receives various data depending on the result of the query in the DB (normally they give results of 3 to 4 data) I have the code structured as follows :
<form autocomplete="off" action="somewhere.php" method="post" onsubmit="return validator();">
<?php
foreach($data["users"] as $dato){
$pco_user= $dato["pco_user"];
?> <p class="card-text"><strong><?php echo $pco_user; ?></strong></p>
<label>Number:</label>
<input type="number" name="votation[]" class="votation"></input><?php
}
?>
<button type="submit" id="submit3" name="button1" class="btn btn-secondary" value="Save" type="button">Save</button>
</form>
In the form tag I have the following code for onsubmit:
<script>
function validator()
{
const controls=document.querySelectorAll('.votation');
let ids=[];
controls.forEach(function(control)
{
event.preventDefault();
if(ids.includes(control.value))
{
alert('Duplicate values');
return true;
}
ids.push(control.value);
return false;
});
}
</script>
Basically what I am achieving at this moment is that the data that is being inserted is read before redirecting to the action of the form reading if there are equal values, but I cannot get that in the event that there are no equal values, I can redirect without problems, Any solution or can you tell me where I'm wrong?
You can prevent form submission by using event.preventDefault() but if the onsubmit function is assigned inline then the event must be passed to the function as a parameter.
You can use Array.every() to find duplicates as explained in this answer.
<form action="script.php" method="post" onsubmit="validator(event)">
<input type="number" class="votation">
<button type="submit">Save</button>
</form>
<script>
function validator(event) {
// get all control input values
const values = document.querySelectorAll('.votation').map(control => control.value);
// check if there are any duplicates
if (!values.every((element, index, array) => array.indexOf(element) === index) {
alert("Duplicate values found");
// prevent form submission
event.preventDefault();
}
}
</script>
Well, seeing your php HTML code you created a close tag for for <input>. HTML <input> tag does not have close tag.
Read more from this
The text field looks like this:
<input type="text" id="nm" name="marks" value="60" onblur="return(myFunction())"/>
the button looks like this:
<input type="submit" value="submit" onclick="val();" />
The following is my function in onblur code:
function myFunction() {
var x = document.getElementById("nm");
if(x.value>12) {
alert("error");
x.value="0";
x.focus();
return false;
}
return true;
}
E.g., if the user changes value of the nm text field and clicks on the next text field then the alert must be shown (if returned false), but in case the user changes value of the the nm field and then clicks on the SUBMIT button, then the function code in the onclick in submit button must not run if onblur returned false. At present, the function in onclick gets executed if onblur returned false.
Please help me with a solution.
Option A:
save onBlur function return into a variable and acces it on the beginning of val() function to know if you have to execute the rest of the code or not.
Option B:
Modify button element interactively on onBlur.
Button with id="button"
<input type="submit" id="button" value="submit" onclick="val();" />
new onBlur function:
function myFunction()
{
var x = document.getElementById("nm");
var button = document.getElementById("button");
if(x.value>12)
{
button.removeAttribute("onclick");
alert("error");
x.value="0";
x.focus();
return false;
}
button.setAttribute("onclick", "val();");
return true;
}
Have in mind both options will require a valid onBlur() after and invalid one for onClick to work again.
I think onclcik function is enough to know value is greater than 12 or not
function val() {
var x = document.getElementById("nm");
if(x.value>12) {
alert("error");
x.value="0";
x.focus();
return false;
}
//do whatever you want
return true;
}
<input type="text" id="nm" name="marks" value="60" />
<input type="submit" value="submit" onclick="val();" />
I have the following search form:
<form method="get" action="SearchResults.asp" id="frmSearch" name="frmSearch">
<input id="q" name="q" type="text" size="50" />
<input type="submit" value="Search" id="button1" name="button1" />
</form>
I add Javascript to the form submit event using the following:
window.onload = function(){
var frm = document.getElementById("frmSearch");
if (window.addEventListener){
frm.addEventListener('submit',function() {validate(frm);} ,false);
}else if (window.attachEvent){
frm.attachEvent('onsubmit', function() {validate(frm);} );
}
}
The validate function is as follows:
function validate(frm) {
alert(frm.id);
var inputs = frm.getElementsByTagName("input");
alert(inputs[0].id);
alert(frm.getElementById("q"));
if (frm.getElementById("q").value=='') {
alert("Please enter your search terms.");
frm.getElementById("q").focus();
return false;
}
frm.getElementById("button1").disabled = true;
return true;
}
The validate function runs but apparently errors out as Javascript ignores the line
frm.getElementById("q")
because alert(frm.id); returns form id "frmSearch", alert(inputs[0].id) returns "q" which is the id of the textbox, but alert(frm.getElementById("q")) does not display anything at all, not even empty alert box.
Can anyone help me diagnose the issue?
getElementById is a method of document, not every HTML element. You'd need to call document.getElementById().
I have a check box in my registration form like this:
<form name="reg" id="reg" method="post">
<input type="checkbox" onclick="return validate('tos')" name="tos"/>
</form>
And I am using JS to check if its ticked, and if so, display a green tick in the form. However, its not actually ticking the check box when its clicked but it is loading the green tick.
Additionally, clicking it a second time doesn't remove the green tick which it should, because the user effectively unticked the check box.
So my JS is this:
function validate (type){
output = [];
var x = document.getElementById("reg");
if (type == 'tos'){
div = 'result_tos';
input = x.elements[4].checked;
if (input){
output.push('<img src="correct.png"/>');
} else {
output.push('You must agree to our terms of service in order to join !');
}
document.getElementById(div).innerHTML = (output.join('')); //display result
}
}
The following jsfiddle is a slightly modified version of your code that seems to be working fine. I don't think your error is here. (I'm not familiar with elements; is that IE specific? I changed that to work on other browsers.)
http://jsfiddle.net/QnDAg/1/
I would approach this as below. Pass a reference to the element from the listener.
<form name="reg" id="reg" method="post">
<input type="checkbox" onclick="return validate(this)" name="tos">
</form>
<script type="text/javascript">
function validate(el) {
// you don't really need a reference to the form,
// but here's how to get it from the element
var form = el.form;
if (el.name == 'tos') {
if (el.checked) {
// show pass graphic (green tick?)
} else {
// hide checkbox and show text
}
}
}
</script>
Swapping between displaying the tick and text should be done by setting a class value, that way you can change it to whatever you want in the markup and the script just toggles the two.
This is probably how I would suggest you do this, which is more complex than the example given, but I'm struggling a little bit with the intended flow and the flow the OP is using:
Mock HTML
<form name="reg" id="reg" method="post">
<input type="checkbox" id="agree" name="agree"/> Agreement<br/>
<input type="checkbox" id="ok" name="ok"/> Ok<br/>
<input type="checkbox" id="tos" name="tos"/> TOS<br/>
<button name="submit" type="submit">Submit Validation</button>
</form>
<h1>Display Output</h1>
<div id="display"></div>
Iterating Validation
function validate (){
var display = document.getElementById('display'),
output = [],
checks = ['agree','ok','tos'],
check,
msg;
while (check = document.reg[checks.pop()]) {
if (!check.checked) {
switch (check.name) {
case 'agree':
msg = 'You must AGREE!';
break;
case 'ok':
msg = 'You must OK!';
break;
case 'tos':
msg = 'You must TOS!';
break;
}
output.push(msg);
}
}
if (output.length == 0) {
output = [
'You have successfully validated!',
'<img src="http://goo.gl/UohAz"/>'
];
}
display.innerHTML = output.join('<br>');
return false;
}
And don't forget the window.onload when you attach the event handler. Below isn't necessarily the preferred preferred method, but it's cleaner than inline handlers like onclick="validate()".
window.onload = function(){
document.reg.onsubmit = validate;
};
http://jsfiddle.net/bj5rj/2
I've got a form that has multiple submit buttons. One for changing data in a database, one for adding, and one for deleting. It looks like this:
<form action="addform.php" method="post" id="addform" onSubmit="return validate(this)">
<select name="listings" id="listings" size="1" onChange="javascript:updateForm()">
<!-- Here I have a php code that produces the listing menu based on a database query-->
</select>
<br />
Price: <input type="text" name="price" id="price" value="0"/><br />
Remarks: <textarea name="remarks" wrap="soft" id="remarks"></textarea><br />
<input type="submit" value="Update Database Listing" name="upbtn" id="upbtn" disabled="disabled"/>
<input type="submit" value="Delete Database Listing" name="delbtn" id="delbtn" disabled="disabled"/>
<br />
<input type="submit" value="Add Listing to Database" name="dbbtn" id="dbbtn"/>
<input type="button" value="Update Craigslist Output" name="clbtn" id="clbtn" onClick="javascript:updatePreview();"/>
</form>
There are actually more elements in the form, but that doesn't matter. What I want to know is, for my validation method, how can I check which submit button has been clicked?
I want it to do the following:
function validate(form){
if (the 'add new listing' or 'update listing' button was clicked'){
var valid = "Are you sure the following information is correct?" + '\\n';
valid += "\\nPrice: $";
valid += form.price.value;
valid += "\\nRemarks: ";
valid += form.remarks.value;
return confirm(valid);}
else {
return confirm("are you sure you want to delete that listing");
}
}
I assume there must be some way to do this relatively easily?
Why don't you set a global variable specifying which button was last clicked? Then you can check this variable in your validate method. Something like:
var clicked;
$("#upbtn").click(function() {clicked = 'update'});
// $("#delbtn").click(function() {clicked = 'delete'});
// ...
function validate(form) {
switch(clicked) {
case 'update':
break;
// more cases here ...
}
}
You can, for example, attach a click event to every submit button that will save a pointer to it in a variable or mark it with a specific attribute / class (it that case you will have to remove that marker from all other submit buttons in the event handler) and then in the submit callback you will know which one was clicked
I think it's easier to just use a click event on each button and handle it individually.
$(function() {
$('input[name=someName]').click(someFunc);
});
function someFunc() {
// Your validation code here
// return false if you want to stop the form submission
}
You could have a hidden field on a form and set the value of that field on clicking the button and then pick it up in your validation routine. You can use jquery to achieve this, let me know if you require an example.
You can use ajax submission with jQuery, you can try something like this:
$('form#addform input[type="submit"]').on('click',function(e){
e.preventDefault();
var current = $(this); //You got here the current clicked button
var form = current.parents('form');
$.ajax({
url:form.attr('action'),
type:form.attr('method'),
data:form.serialize(),
success:function(resp){
//Do crazy stuff here
}
});
});