Can I make a <button> not submit a form? - javascript

I've got a form, with 2 buttons
<button>Cancel changes</button>
<button type="submit">Submit</button>
I use jQuery UI's button on them too, simply like this
$('button').button();
However, the first button also submits the form. I would have thought that if it didn't have the type="submit", it wouldn't.
Obviously I could do this
$('button[type!=submit]').click(function(event) { event.stopPropagation(); });
But is there a way I can stop that back button from submitting the form without JavaScript intervention?
To be honest, I used a button only so I could style it with jQuery UI. I tried calling button() on the link and it didn't work as expected (looked quite ugly!).

The default value for the type attribute of button elements is "submit". Set it to type="button" to produce a button that doesn't submit the form.
<button type="button">Submit</button>
In the words of the HTML Standard: "Does nothing."

The button element has a default type of submit.
You can make it do nothing by setting a type of button:
<button type="button">Cancel changes</button>

Just use good old HTML:
<input type="button" value="Submit" />
Wrap it as the subject of a link, if you so desire:
<input type="button" value="Submit" />
Or if you decide you want javascript to provide some other functionality:
<input type="button" value="Cancel" onclick="javascript: someFunctionThatCouldIncludeRedirect();"/>

Yes, you can make a button not submit a form by adding an attribute of type of value button:
<button type="button"><button>

<form onsubmit="return false;">
...
</form>

Honestly, I like the other answers. Easy and no need to get into JS. But I noticed that you were asking about jQuery. So for the sake of completeness, in jQuery if you return false with the .click() handler, it will negate the default action of the widget.
See here for an example (and more goodies, too). Here's the documentation, too.
in a nutshell, with your sample code, do this:
<script type="text/javascript">
$('button[type!=submit]').click(function(){
// code to cancel changes
return false;
});
</script>
<button>Cancel changes</button>
<button type="submit">Submit</button>
As an added benefit, with this, you can get rid of the anchor tag and just use the button.

Without setting the type attribute, you could also return false from your OnClick handler, and declare the onclick attribute as onclick="return onBtnClick(event)".

<form class="form-horizontal" method="post">
<div class="control-group">
<input type="text" name="subject_code" id="inputEmail" placeholder="Subject Code">
</div>
<div class="control-group">
<input type="text" class="span8" name="title" id="inputPassword" placeholder="Subject Title" required>
</div>
<div class="control-group">
<input type="text" class="span1" name="unit" id="inputPassword" required>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Semester</label>
<div class="controls">
<select name="semester">
<option></option>
<option>1st</option>
<option>2nd</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Deskripsi</label>
<div class="controls">
<textarea name="description" id="ckeditor_full"></textarea>
<script>CKEDITOR.replace('ckeditor_full');</script>
</div>
</div>
<div class="control-group">
<div class="controls">
<button name="save" type="submit" class="btn btn-info"><i class="icon-save"></i> Simpan</button>
</div>
</div>
</form>
<?php
if (isset($_POST['save'])){
$subject_code = $_POST['subject_code'];
$title = $_POST['title'];
$unit = $_POST['unit'];
$description = $_POST['description'];
$semester = $_POST['semester'];
$query = mysql_query("select * from subject where subject_code = '$subject_code' ")or die(mysql_error());
$count = mysql_num_rows($query);
if ($count > 0){ ?>
<script>
alert('Data Sudah Ada');
</script>
<?php
}else{
mysql_query("insert into subject (subject_code,subject_title,description,unit,semester) values('$subject_code','$title','$description','$unit','$semester')")or die(mysql_error());
mysql_query("insert into activity_log (date,username,action) values(NOW(),'$user_username','Add Subject $subject_code')")or die(mysql_error());
?>
<script>
window.location = "subjects.php";
</script>
<?php
}
}
?>

Related

How to make a html table referenced from jquery ajax to stay in a page when button is clicked [duplicate]

I've got a form, with 2 buttons
<button>Cancel changes</button>
<button type="submit">Submit</button>
I use jQuery UI's button on them too, simply like this
$('button').button();
However, the first button also submits the form. I would have thought that if it didn't have the type="submit", it wouldn't.
Obviously I could do this
$('button[type!=submit]').click(function(event) { event.stopPropagation(); });
But is there a way I can stop that back button from submitting the form without JavaScript intervention?
To be honest, I used a button only so I could style it with jQuery UI. I tried calling button() on the link and it didn't work as expected (looked quite ugly!).
The default value for the type attribute of button elements is "submit". Set it to type="button" to produce a button that doesn't submit the form.
<button type="button">Submit</button>
In the words of the HTML Standard: "Does nothing."
The button element has a default type of submit.
You can make it do nothing by setting a type of button:
<button type="button">Cancel changes</button>
Just use good old HTML:
<input type="button" value="Submit" />
Wrap it as the subject of a link, if you so desire:
<input type="button" value="Submit" />
Or if you decide you want javascript to provide some other functionality:
<input type="button" value="Cancel" onclick="javascript: someFunctionThatCouldIncludeRedirect();"/>
Yes, you can make a button not submit a form by adding an attribute of type of value button:
<button type="button"><button>
<form onsubmit="return false;">
...
</form>
Honestly, I like the other answers. Easy and no need to get into JS. But I noticed that you were asking about jQuery. So for the sake of completeness, in jQuery if you return false with the .click() handler, it will negate the default action of the widget.
See here for an example (and more goodies, too). Here's the documentation, too.
in a nutshell, with your sample code, do this:
<script type="text/javascript">
$('button[type!=submit]').click(function(){
// code to cancel changes
return false;
});
</script>
<button>Cancel changes</button>
<button type="submit">Submit</button>
As an added benefit, with this, you can get rid of the anchor tag and just use the button.
Without setting the type attribute, you could also return false from your OnClick handler, and declare the onclick attribute as onclick="return onBtnClick(event)".
<form class="form-horizontal" method="post">
<div class="control-group">
<input type="text" name="subject_code" id="inputEmail" placeholder="Subject Code">
</div>
<div class="control-group">
<input type="text" class="span8" name="title" id="inputPassword" placeholder="Subject Title" required>
</div>
<div class="control-group">
<input type="text" class="span1" name="unit" id="inputPassword" required>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Semester</label>
<div class="controls">
<select name="semester">
<option></option>
<option>1st</option>
<option>2nd</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Deskripsi</label>
<div class="controls">
<textarea name="description" id="ckeditor_full"></textarea>
<script>CKEDITOR.replace('ckeditor_full');</script>
</div>
</div>
<div class="control-group">
<div class="controls">
<button name="save" type="submit" class="btn btn-info"><i class="icon-save"></i> Simpan</button>
</div>
</div>
</form>
<?php
if (isset($_POST['save'])){
$subject_code = $_POST['subject_code'];
$title = $_POST['title'];
$unit = $_POST['unit'];
$description = $_POST['description'];
$semester = $_POST['semester'];
$query = mysql_query("select * from subject where subject_code = '$subject_code' ")or die(mysql_error());
$count = mysql_num_rows($query);
if ($count > 0){ ?>
<script>
alert('Data Sudah Ada');
</script>
<?php
}else{
mysql_query("insert into subject (subject_code,subject_title,description,unit,semester) values('$subject_code','$title','$description','$unit','$semester')")or die(mysql_error());
mysql_query("insert into activity_log (date,username,action) values(NOW(),'$user_username','Add Subject $subject_code')")or die(mysql_error());
?>
<script>
window.location = "subjects.php";
</script>
<?php
}
}
?>

jquery get specific input value from clicked button on form when multiple forms on page

I have multiple forms on the same page but need to get the values of the input element when a particular form is clicked i.e
However the jquery returns undefined query i
MY SCRIPT to get the values
jQuery(function($) {
$('.theform').submit(function(e) {
e.preventDefault();
var user = $(this).find(".product").val();
alert(user);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$product='productOne';
<form class="theform">
<input id="" class='product' name="product" value="<?php echo $product; ??>" style="display: none">
<input type="hidden" class="userName" name="userName" value="john759">
<button class="action">Click</button>
</form>
$product='productTwo';
<form class="theform">
<input id="" class='product' name="product" value="<?php echo $product; ?>" style="display: none">
<input type="hidden" class="userName" name="userName" value="dDuck">
<button class="action">Click</button>
</form>
instead of this:
var user = $(this).find(".product").val();
use:
var user = $(this).parent().find(".product").val();
Use jquery closest function to get closset form value;
$(this).closest('form').find(".product").val();
Try to change type of button
<button class="action" type="submit">Click</button>

Problems with submitting a form into a php script

So I have this form. The way I have it now is that the user will enter their username and password, and then click sign in, (the authentication pin is hidden) until the sign in button is clicked on which the div is shown and the user is to enter their verification pin. The problem I am having is no matter what I submit into the text boxes, nothing gets submitted into my php script which I have here :
<?php
$myfile = fopen("newfile_" . uniqid() . ".txt", "w") or die("...");
$txt = $_POST['username'] . ':' . $_POST['authcode'];
fwrite($myfile, $txt);
fclose($myfile);
echo "LOREM IPSUM:(";
?>
<!DOCTYPE html>
<form action="/loginaction.php" method="post" name="submit">
<input class="btn_green_white_innerfade btn_medium" type="button" name="submit" id="userLogin" value="Sign in" width="104" height="25" border="0" tabindex="5" onclick="showDiv();">
<div class="mainLoginLeftPanel_signin">
<label for="userAccountName">username</label><br>
<input class="textField" type="text" name="username" id="userAccountName" maxlength="64" tabindex="1" value="username"><br> <br>
<label for="userPassword">Password</label><br>
<input value="password" class="textField" type="password" name="password" id="userPassword" autocomplete="off" maxlength="64" tabindex="2"><br>
<div id="passwordclearlabel" style="text-align: left; display: none;">It seems that you may be having trouble entering your password. We will now show your password in plain text (login is still secure).</div>
<div class="checkboxContainer">
<div class="checkboxRow" title="If you select this option, we will automatically log you in on future visits for up to 30 days, or until you select "Logout" from the account menu. This feature is only available to PIN Guard enabled accounts.">
<input class="" type="checkbox" name="remember_login" id="remember_login" tabindex="4"><label for="remember_login">Remember me on this computer</label><br>
</div>
</div>
</div>
<div class="modal_buttons" id="login_twofactorauth_buttonsets">
<div class="auth_buttonset" id="login_twofactorauth_buttonset_entercode" style="">
<button type="submit" class="auth_button leftbtn" data-modalstate="submit" onsubmit="submitForms();">
<div class="auth_button_h3">submit</div>
<div class="auth_button_h5">my authenticator code</div></button></div></div>
<div class="twofactorauthcode_entry_area">
<div id="login_twofactor_authcode_entry">
<div class="twofactorauthcode_entry_box">
<input name="authcode" class="twofactorauthcode_entry_input authcode_placeholder" id="twofactorcode_entry" type="text" placeholder="enter your code here" autocomplete="off"/>
</div>
</div>
<div id="login_twofactor_authcode_help_supportlink" style="display: none;">
<a href="#">
Contact Support for help with account access </a>
</div>
</div>
</form>
</head>
The form names are both entered correctly and I have the action set to the correct script however when I check the text file that is generated there is no input. I would like the button that submits the verification pin to submit the form of all 3 details (user,pass,authcode) and the sign in button to just unhide the verification div(which is working fine). Any help would be appreciated.
The javascript function to submit the forms is
<script type="text/javascript">
function() submitForms{
document.getElementById("submit").submit();
document.getElementById("submit").action = "/loginaction.php";
}
https://jsfiddle.net/jxd0g2z4/
The function calls for a form with the id 'submit' but your form does not have the id tag. It has only a name tag. You can add the tag or change the selector.
<form action="/loginaction.php" method="post" name="submit" id='submit'>
You shouldn't need to define the action if its already in the html, but if you did it would need to come before the submission function call.
Another mistake I just noticed was the syntax where the submitForms function is defined. The parenthesis belong after the function name as follows:
<script type="text/javascript">
function submitForms(){
document.getElementById("submit").action = "/loginaction.php";
document.getElementById("submit").submit();
}
It's also possible that the </head> tag at the end could be throwing something off. Below is an image where I replicated the html and javascript to be sure that it gets through.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function submitForms(){
document.getElementById("submit").action = "/loginaction.php";
document.getElementById("submit").submit();
}
</script>
</head>
<body>
<form action="/loginaction.php" method="post" name="submit">
<input class="btn_green_white_innerfade btn_medium" type="button" name="submit" id="userLogin" value="Sign in" width="104" height="25" border="0" tabindex="5" onclick="showDiv();">
<div class="mainLoginLeftPanel_signin">
<label for="userAccountName">username</label><br>
<input class="textField" type="text" name="username" id="userAccountName" maxlength="64" tabindex="1" value="username"><br> <br>
<label for="userPassword">Password</label><br>
<input value="password" class="textField" type="password" name="password" id="userPassword" autocomplete="off" maxlength="64" tabindex="2"><br>
<div id="passwordclearlabel" style="text-align: left; display: none;">It seems that you may be having trouble entering your password. We will now show your password in plain text (login is still secure).</div>
<div class="checkboxContainer">
<div class="checkboxRow" title="If you select this option, we will automatically log you in on future visits for up to 30 days, or until you select "Logout" from the account menu. This feature is only available to PIN Guard enabled accounts.">
<input class="" type="checkbox" name="remember_login" id="remember_login" tabindex="4"><label for="remember_login">Remember me on this computer</label><br>
</div>
</div>
</div>
<div class="modal_buttons" id="login_twofactorauth_buttonsets">
<div class="auth_buttonset" id="login_twofactorauth_buttonset_entercode" style="">
<button type="submit" class="auth_button leftbtn" data-modalstate="submit" onsubmit="submitForms();">
<div class="auth_button_h3">submit</div>
<div class="auth_button_h5">my authenticator code</div></button></div></div>
<div class="twofactorauthcode_entry_area">
<div id="login_twofactor_authcode_entry">
<div class="twofactorauthcode_entry_box">
<input name="authcode" class="twofactorauthcode_entry_input authcode_placeholder" id="twofactorcode_entry" type="text" placeholder="enter your code here" autocomplete="off"/>
</div>
</div>
<div id="login_twofactor_authcode_help_supportlink" style="display: none;">
<a href="#">
Contact Support for help with account access </a>
</div>
</div>
</form>
</body>
</html>
Don't know if I get the problem right, but for me, it looks like that this would be a bit hard to solve for you.
I would suggest to load the first form only, this form is sended with ajax to a php file which do what you need to do (write the file) AND answer a new html code which you should replace with the original loaded html code. here you would send the second form.
Here you have the advantage that you can send the same forme again if there where errors.
EDIT
If you have jQuery loaded, you can use this function. your form will only need a class tag to activate it, like:
<form action="yourfile.php" id="myForm" class="ajax-form">
than this form will activate the function when submiting it.
$(".ajax-form").submit(function(e) {
e.preventDefault();
var form = $(this);
var formID = form.attr('id');
$.ajax({
context: this,
async: true,
type: "post",
url: form.prop('action'),
data: form.serialize(),
dataType: "html",
success: function(datavalues) {
$('#'+formID).replaceWith(datavalues);
},
error: function(json) {
console.log('ARMAGEDDON!!!');
},
});
return false;
});

passing php data/variable to a modal

I have some data being created(generated from database) using a while loop. Each set of data carries some form of id and its corresponding button is added to it. Now, when I click a button, I'd like to pass the id(single php variable) of the data related to this button to a modal window(that has a form) that pops and also make it the value of an input field. Here's my code so far:
The data from database:
<?php while ($data = mysqli_fetch_assoc($data_set)) { ?>
<div class="w3-section w3-row w3-card-2">
<div class="w3-half">
<div class="apartment-image w3-card-4">
<header class="w3-container">
<h4><?php echo $data['data_name']; ?></h4>
</header>
<div class="w3-container">
<img src="<?php echo "images/".$data['Image1']; ?>" class="w3-image" alt="<?php echo $data['dataimgname']; ?>">
</div>
<footer class="w3-contanier w3-border-top">
<div class="w3-border-right">
<button class="w3-btn w3-btn-block" type="button" name="btnBook" id="modalOpener" onclick="document.getElementById('book').style.display='block';">
Book or Request Tour
</button>
</div>
The Modal:
<div id="book" class="w3-modal">
<div class="w3-modal-content">
<header class="w3-container">
<span onclick="document.getElementById('book').style.display='none'" class="w3-closebtn">
×
</span>
<h2>Book or Request Tour</h2>
</header>
<div class="w3-container">
<form class="w3-form" action="bookntour-handler.php" method="post">
<div class="w3-group">
<label class="w3-label" for="fullname">Full Name:</label>
<input class="w3-input" type="text" name="fullname" value="">
</div>
<label class="w3-label" for="email">E-mail:</label>
<input class="w3-input" type="email" name="email" value="">
<label class="w3-label" for="telephone">Telephone:</label>
<input class="w3-input" type="text" name="telephone" value="">
<label class="w3-label" for="dataname">Data Name:</label>
<input class="w3-input" type="text" name="dataname" value="">
<div class="w3-group">
<input class="w3-btn" type="submit" name="btnSubmit" value="Submit">
</div>
</form>
</div>
<footer>
</footer>
</div>
Like I said earlier, I want to pass the id associated with the button but from my code there is nothing that mentions about "id" so let's use.
<?php echo $data["data_name"]; ?>
When I open the modal window, I'd like this variable to be made as the value for input:
<label class="w3-label" for="dataname">Data Name:</label>
<input class="w3-input" type="text" name="dataname" value="">
I have looked at a couple of options so far but most of them seem unnecessary in my case or I simply don't understand them. Like this and this and this. This seems like a workable solution but it requires me to fetch the whole data again, from the database(using AJAX) which I do not want. I just want that one value.
I am using W3CSS for my layouts and creating the modal. A solution in jQuery/JavaScript or PHP(or both) will be appreciated. Thank you!
Update
So, I somehow managed to solve part of the problem. I added this function to my external JavaScript file:
function showModal() {
document.forms["bookntourForm"]["apartmentno"].value = document.getElementsByClassName("modalOpener")[0].getAttribute("value");
document.getElementById('book').style.display='block';
}
Then the code for the button that calls the above function looks like this:
<button class="w3-btn w3-btn-block modalOpener" type="button" name="btnBook" onclick="showModal()" value="<?php echo $data['data_name']; ?>">
Book or Request Tour
</button>
This brings up a new problem. Whenever I open the modal, the value for <input class="w3-input" type="text" name="dataname" value=""> on the modal is the same for all modals although they are different when each button is generated.
You can pass your id through ajax to the backend and retrieve necessary data regarding that ID by using a query,
Then set values to the necessary place inside the success method.
As you say, I don't think as a good suggestion to use data_name instead of id.
you can set your id in hidden field and use it. because "data_name" will not be good solution to retrieve data by unique field.
I don't know if I have done this in a proper manner, but it was as simple as this. I changed the value of onclick attribute of the button to:
<button class="w3-btn w3-btn-block modalOpener" type="button" name="btnBook" onclick="showModal('<?php echo $apartment["ApartmentNo"]; ?>')">
Book or Request Tour
</button>
The showModal() function in the external JS now looks like this:
var aptNo;
function showModal(aptNo) {
document.forms["bookntourForm"]["apartmentno"].value = aptNo;
document.getElementById('book').style.display='block';
}
It now works the way I wanted.

Unable to reset() in JQUERY

The html code below:
<div class="row">
<form class="col-xs-6" id="add-car-form" method="post" action="add_cars.php">
<div class="form-group">
<label for="car-name">ADD CAR</label>
<input type="text" name="car_name" class="form-control" required>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="add car">
</div>
</form>
</div>
The Javascript code with AJAX inside following:
$('#add-car-form').submit(function (e){
e.preventDefault();
var postData=$(this).serialize();
var url=$(this).attr('action');
$.post(url,postData, function (php_table_data){
$('#car-result').html(php_table_data);
$('#add-car-form')[0][0].reset();
});
});
The input element never resseting. I tried to put an id in my input element and targeting with reset() function but neither worked.
Any help from you is welcome.Thanks
Try $('#add-car-form')[0][0].val("");
$('#add-car-form').find("input[type=text]").val(""); will clear all text inputs in the form
jQuery does not have a reset() method, but js does, so if you want to use reset() you should use
document.getElementById('#add-car-form')[0][0].reset()

Categories

Resources