I am taking a variable from an HTML form element and trying to put it into a div to be displayed on the website whenever I click a button. However it shows up for a second then pops away.
I tried taking it out of the document.ready() block but that didn't work. When I put a string literal in the $(".output").html the same problem occurs as well. Similar questions like mine seem to be a syntax error, but I don't seem to have any I can find.
$(document).ready(function(){
$(".sub").on("click",function(){
var searchstring = $("#searchfield");
$(".output").html(searchstring.val());
});
});
Here is my site on codepen: http://codepen.io/arcjackson06/pen/NNeQvJ
Your <button> will submit the surrounding form. You need to use:
<button class="..." type="button"></button>
Which will prevent the form from submitting when clicked.
Alternative you can prevent the default click event, with:
$('.sub').on('click', function(event) {
event.preventDefault();
// ...
This should do the trick:
$(".sub").on("click",function(e)
{
e.preventDefault();
var searchstring = $("#searchfield").val();
$(".output").html(searchstring);
}
No need for any extra JavaScript.
Just give your button an attribute type="button" and that should take care of it.
The problem is a button's default type is submit so you are refreshing the page.
The issue is that the form on your page is submitting every time someone clicks that search button. To prevent that you need to use event.preventDefault:
$(".sub").on("click",function(event){
event.preventDefault();
var searchstring = $("#searchfield");
$(".output").html(searchstring.val());
When someone is clicking on , Its submitting the form and your page is getting reloaded. If you donot want to submit the form
You can try this.
$(document).ready(function(){
$(".sub").on("click",function( event ){
var searchstring = $("#searchfield");
$(".output").html(searchstring.val());
event.preventDefault(); // This will prevent the form submission
});
});
It's refreshing the form. That's why you don't see value. See updated codepen : http://codepen.io/anon/pen/vGwNJP
I added return false as follows:
$(document).ready(function(){
$(".sub").on("click",function(e){
var searchstring = $("#searchfield");
$("#output").html(searchstring.val());
return false;
// Or e.preventDefault();
});
});
Alternatively, you can add e.preventDefault(); as well.
As you are using form it would try to do forms default action i.e. submit.
Here you need to do event.preventDefault in onclick handler.
Related
Please pardon me if it is a basic thing, because I am a new learner of Javascript/jQuery. I have been trying to disable submit button to disable multiple submits. I have come across multiple solutions here as well, but all those used specific form name. But I wanted to apply a global solution for all forms on all pages so I dont have to write code on each page, so I put this in footer, so all pages have:
$('input:submit').click(function(){
$('input:submit').attr("disabled", true);
});
This code works on all the forms in all pages as I wanted, but if there are HTML5 required fields in form and form is submitted without them, of course notifications are popped but button still gets disabled. So, I tried with this:
$('input:submit').click(function(){
if ($(this).valid()) {
$('input:submit').attr("disabled", true);
$('.button').hide();
});
});
But this does not work. Kindly help me so that jQuery only disables when all HTML5 validation is done. Thanks
Try this and let me know:
$('input:submit').click(function(){
if ($(this).closest("form").checkValidity()) {
$('input:submit').attr("disabled", true);
$('.button').hide();
});
});
Ruprit, thank you for the tip. Your example did not work for me (in Firefox), but it helped me a lot.
Here is my working solution:
$(document).on("click", ".disable-after-click", function() {
var $this = $(this);
if ($this.closest("form")[0].checkValidity()) {
$this.attr("disabled", true);
$this.text("Saving...");
}
});
Since checkValidity() is not a jQuery function but a JavaScript function, you need to access the JavaScript element, not the jQuery object. That's the reason why there has to be [0] behind $this.closest("form").
With this code you only need to add a class="disable-after-click" to the button, input, link or whatever you need...
It is better to attach a handler to the submit event rather than a click event, because the submit event is only fired after validation is successful. (This saves you from having to check validity yourself.)
But note that if a submit button is disabled then any value they may hold is NOT submitted to the server. So we need to disable the inputs after form submission.
The question is compounded by the new HTML5 attribute form which allows associated inputs to be anywhere on the page as long as their form attribute matches a form ID.
This is the JQuery snippet that I use:
$(document).ready( function() {
$("form").on("submit", function(event) {
var $target = $(event.target);
var formId = $target.attr("id");
// let the submit values get submitted before we disable them
window.setTimeout(function() {
// disable all submits inside the form
$target.find("[type=submit]").prop("disabled", true);
// disable all HTML5 submits outside the form
$("[form=" + formId + "][type=submit]").prop("disabled", true);
}, 2); // 2ms
});
});
---[ WARNING ]---
While disabling submit buttons prevents multiple form submissions, the buttons have the unfortunate side effect of staying disabled should the user click the [Back] button.
Think about this scenario, the user edits some text, clicks submit (and get redirected to different page to view the edits), clicks back to edit some more, ... and ... they can't re-submit!
The solution is to (re-)enable the submit button on page load:
// re-enable the submit buttons should the user click back after a "Save & View"
$(document).ready( function() {
$("form").each(function() {
var $target = $(this);
var formId = $target.attr("id");
// enable all submits inside the form
$target.find("[type=submit]").prop("disabled", false);
// enable all HTML5 submits outside the form
$("[form=" + formId + "][type=submit]").prop("disabled", false);
});
});
Try this
`jQuery('input[type=submit]').click(function(){ return true;jQuery(this).prop('disabled','disabled');})`
run this code on successful validation of the form
I have a simple HTML button on my form, with script as follows:
$(document).ready(function () {
$("#btn1").click(function () {
$("#btn1").text("Button clicked");
return false;
});
});
With the return false, it works as I expect - I click the button, and its text changes to 'Button clicked'. Without the 'return false', it changes, but then changes back.
Complete JQuery noob here, why do I need the 'return false'?
A <button> in a form submits the form, which is why it turns back, the page reloads resetting everything javascript changed, so you see the change, and it immediately reloads the page when the form submits.
The return false prevents the form from submitting when clicking the button.
Note: the <button> element has a default type of submit, so it will always submit the form it's nested inside.
Like #adeneo said, your form is being sent out so the page will reload. Additionally, if you don't want to use return false; you can use preventDefault() by passing an event parameter to your function as such:
$(document).ready(function () {
$("#btn1").click(function (ev) {
ev.preventDefault();
$("#btn1").text("Button clicked");
});
});
Hope this helps,
If the <button> was not intended to submit the form, then instead of using return false; or other workarounds make the button the proper type.
<button id="btn1" type="button">
And it will stop submitting when clicked. The reason it does now is because the button's default type is submit (it has 3 possible types: submit, button, and reset).
I'm using the following script to check if the forms content has changed to prevent the user from browsing away without saving their changes.
<script type="text/javascript">
var isDirty = false;
var msg = 'You have unsaved changes.';
$(document).ready(function(){
$(':input').change(function(){
if(!isDirty){
isDirty = true;
}
});
window.onbeforeunload = function(){
if(isDirty){
return msg;
}
};
});
</script>
The Save button currently looks like this:
<input type="submit" name="frmProjectAction" value="Save" onclick='selectAll(frmProjectResources,true);' />
This is working for the most part but I have two issues:
1. It fires even when the user clicks the Save button on my form. How can I prevent this?
2. It isn't detecting changes in the TinyMCE text box I have on my form. How can I detect changes in the TinyMCE text box as well as all the other fields on my form?
Thanks in advance - Dave
1: use a click() jquery function on the save button that sets isDirty to false. You need to add an id or a class to your save button first so you can target it with jquery. Let's say that you set the save button id to "savebutton" then you do the following:
$('#savebutton').click(function(){
selectAll(frmProjectResources,true); // <-- from your onclick="" attribute
isDirty = false;
})
you can notice that we have moved the selectAll(...) part from the onclick attribute of the save button to the jquery. Hence, you should remove the onclick attribute from the button.
2: TinyMCE has onchange_callback which you can use fire a function which sets isDirty to true. The onchange_callback is set when you initialize TinyMCE, and you give it the name of the function you want to fire whan the form is changed.
//first define the function
function setIsDirty(){
isDirty = true;
}
// then init the tinyMCE
tinyMCE.init({
... // some parameters
onchange_callback : "setIsDirty"
});
This way, you can control precicely what happens when editor is changed. If you just need to check if it has been edited or not before leaving the page, you can also use TinyMCE's own isDirty method
This is really only a solution to question number 1:
You would need one additional event handler, the one for onsubmit on your form.
In that event handler, you update isDirty to false (since you are saving the form now.. so it's no longer "dirty")
I can't comment on tinyMCE, as I've never worked with that.
plugins: "autosave"
autosave_ask_before_unload: true
toolbar: "restoredraft"
http://jsfiddle.net/wmuYq/
I want to eliminate an awkwardness: the user has to click the submit button twice to submit the text.
What should I do to make it work with one click?
You can set a timeout: http://jsfiddle.net/wmuYq/1/
document.getElementById("text1").onblur = function () {
var target = this;
setTimeout( function () {
target.style.height='36px';
}, 250);
}
You could use the onmousedown event on the submit button to submit the form:
document.getElementById("submitButton").onmousedown = function() {
this.form.submit();
}
For the above example to work, you would need to give the button an ID. Also, you would need to change the name of the submit button from "submit" to something else, because otherwise it overwrites the submit property of the form element.
This works because the mousedown event will be triggered on the button before the blur event is triggered by the textarea.
Here's a working example.
Well for one thing you have no form, so I am not sure how it submits at all.
Wrap your code in a form and add an action and it should work fine :-)
This might work. Untested
Remove the onblur event from the textarea and place it as on onclick on the input
onclick="document.getElementById('text1').style.height='36px'"
Revised fiddle: http://jsfiddle.net/jasongennaro/wmuYq/2/
I'm using asp.net MVC and when I submit a form, a previous developer had embedded some jQuery validation.
$('form').submit(function() {
...code done here to validate form fields
});
The problem is that both the "Save" and "Cancel" buttons on the form fire this submit jQuery function. I don't want the validation logic to fire if the "Cancel" input button was fired (id="cancel" name="cancel" value="cancel").
Is there a way that, within this submit function, I can retrieve the ID, name or value of which input button was pressed to submit the form?
I asked this same question: How can I get the button that caused the submit from the form submit event?
The only cross-browser solution I could come up with was this:
$(document).ready(function() {
$("form").submit(function() {
var val = $("input[type=submit][clicked=true]").val()
// DO WORK
});
$("form input[type=submit]").click(function() {
$("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
Not sure if its the answer you're looking for but you should change the "Cancel" button to an anchor tag. There's no need to submit a cancel unless you're doing work on the form values.
well this will only fire if the type of the input button is like so:
<input type='submit' ...
so make sure the cancel button does not have type='submit' and it should work
EDIT
This only works in FF and not in Chrome (and I so, I imagine, not in other WebKit based browsers either) so I'm just leaving this here as a browser specific workaround, an interesting note but not as the answer.
#Neal's suggestion of NOT making the cancel button of type submit is probably the cleanest way. However, if you MUST do it the way you are doing it now:
$('form').submit(function(e){
if(e.originalEvent.explicitOriginalTarget.id === 'cancel'){
//don't validate
}
else{
//validate
}
});
var myForm = $('form');
$('input[type="submit"]',myForm).click(function(e) {
var whoClickedsubmit = $(e.target); //further, you can use .attr('id')
//do other things here
});
EDIT
.submit(function(event){
var target = event.originalEvent.explicitOriginalTarget.value;
//But IE does not have the "explicitOriginalTarget" property
});