Submit form without page reloading, and link to javascript - javascript

I have made a system that when you enter a specific value, it'll fade in values based on the selection.
I have this code here which is the main form where you can input the specific model numbers into the form and then press enter.
<form>
<input type="text" name="ModNum" id="ModelNumber" pattern="^PIV13RT[23]?$"
title="Your Model Number." placeholder="Please Input a Model number" size="35" maxlength="8">
<center><span class="egsmall"><strong>Eg: PIV13RT, PIV13RT2, Ect.</strong></span></center>
<center><div class="btnwrap"><input name="proceed" type="submit" class="submitsup" id="forward" /></div></center>
</form>
The problem is that when you press enter, because it's inside of a form, it reloads the page, which means that the fade in won't load because it's reloading the page.
$("#forward").click(function(){
$.ajax({
}).done(function() {
$('.optionbk').fadeIn('slow');
});
});
I realise that this can also be done with Javascript, but that wouldn't allow me to use a Form.
$("#forward").click(function(){
var text = $("#ModelNumber").val();
var comparingText = "PIV13RT";
var comparingText2 = "PIV13RT2";
var comparingText3 = "PIV13RT3";
if (text == comparingText) {
$('.optionbk').fadeIn('slow');
}
if (text == comparingText2) {
$('.optionbk').fadeIn('slow');
}
if (text == comparingText3) {
$('.optionbk').fadeIn('slow');
}
});
Is there anyway that I can do it inside of a form, but make it so that the page doesn't reload itself so that the fade works instead of reloading. The form is needed because it is following that specific pattern. Please note that the form isn't linking to an external PHP file.

The quickest solution is to add onsubmit="return false" into your opening <form> tag.

You should bind your callback function to the submit event that the form dispatches and make it return false to cancel the actual submission.
$('form').bind('submit', function(){
$.ajax();
return false;
});

Related

Make the click-button code not disappear instantly? [duplicate]

I have a button (<input type="submit">). When it is clicked the page reloads. Since I have some jQuery hide() functions that are called on page load, this causes these elements to be hidden again. How do I make the button do nothing, so I can still add some action that occurs when the button is clicked but not reload the page.
There is no need to use JS or jQuery.
to stop the page to reload, just specify the button type as 'button'.
If you don't specify the button type, the browser will automatically set it to 'reset' or 'submit' which causes the page to reload.
<button type='button'>submit</button>
Use either the <button> element or use an <input type="button"/>.
In HTML:
<form onsubmit="return false">
</form>
in order to avoid refresh at all "buttons", even with onclick assigned.
You could add a click handler on the button with jQuery and do return false.
$("input[type='submit']").click(function() { return false; });
or
$("form").submit(function() { return false; });
In HTML:
<input type="submit" onclick="return false">
With jQuery, some similar variant, already mentioned.
You can use a form that includes a submit button. Then use jQuery to prevent the default behavior of a form:
$(document).ready(function($) {
$(document).on('submit', '#submit-form', function(event) {
event.preventDefault();
alert('page did not reload');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form id='submit-form'>
<button type='submit'>submit</button>
</form>
You could also use JavaScript for that:
let input = document.querySelector("input");
input.addEventListener("submit", (event) => {
event.preventDefault();
})
As stated in one of the comments (burried) above, this can be fixed by not placing the button tag inside the form tag. When the button is outside the form, the page does not refresh itself.
I can't comment yet, so I'm posting this as an answer.
Best way to avoid reload is how #user2868288 said: using the onsubmit on the form tag.
From all the other possibilities mentioned here, it's the only way which allows the new HTML5 browser data input validation to be triggered (<button> won't do it nor the jQuery/JS handlers) and allows your jQuery/AJAX dynamic info to be appended on the page.
For example:
<form id="frmData" onsubmit="return false">
<input type="email" id="txtEmail" name="input_email" required="" placeholder="Enter a valid e-mail" spellcheck="false"/>
<input type="tel" id="txtTel" name="input_tel" required="" placeholder="Enter your telephone number" spellcheck="false"/>
<input type="submit" id="btnSubmit" value="Send Info"/>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#btnSubmit').click(function() {
var tel = $("#txtTel").val();
var email = $("#txtEmail").val();
$.post("scripts/contact.php", {
tel1: tel,
email1: email
})
.done(function(data) {
$('#lblEstatus').append(data); // Appends status
if (data == "Received") {
$("#btnSubmit").attr('disabled', 'disabled'); // Disable doubleclickers.
}
})
.fail(function(xhr, textStatus, errorThrown) {
$('#lblEstatus').append("Error. Try later.");
});
});
});
</script>
Use event.preventDefault() in the first line of your event function.
Buttons must be of the type button and contain type="submit" in the button html.

Bootstrap Form Always Submits on Enter

I have a jquery function:
$("#get-input").keyup(function (event) {
if (event.keyCode === 13) {
$("#get-data").click();
}
});
$("#get-data").click(function (e) {
var endpoint = $(".get-input").val();
if ($('#data-display').is('[hidden]')) {
$('#data-display').removeAttr('hidden');
}
$.ajax
({
url: "https://localhost:44398/api/" + endpoint,
type: 'get',
success: function (data) {
$('.formatted-json').text(JSON.stringify(data, null, '\t'))
}
});
});
My form:
<form class="form-inline">
<div class="form-group query-container">
<label class="get-lbl pr-2">this is the label</label>
<input type="text" class="form-control-lg get-input" placeholder="placeholder" />
<input type="button" class="btn btn-orange btn-get" id="get-data" value="submit" />
</div>
</form>
This works perfectly when I click the #get-data button. The ajax is hit, and the data is displayed. My issue is that when I hit the enter key, it reloads the entire page. I need the enter key to act the same as if I clicked the button.
I have tried changing the keyup to keydown and keypress without luck. I have tried changing the .click function to a .submit function on the form instead of the input. I have also wrapped all the JS inside a document ready call, but it still works the same.
Does anyone have any ideas what I need to do to get this working properly when I press enter?
This is not quite an answer, but it's the best I could come up with. If someone has a better solution, I will happily mark it as the answer instead of this!
I ended up adding onsubmit="return false" to my opening form tag.
This ensured that the user could not press enter to submit the form. So the user can now only submit the form by clicking on the button which will trigger the jQuery click function.

If the text-box value in HTML5 form is x, then y: Is that possible?

So basically, I want to enter a certain string into a text-box, and check what it is. It's basically for a command system that I'm trying to implement. There's a little Terminal pop-up and there is a text-box in it waiting for a command. This is the HTML I used to make the text-box inside a form:
<form id="command-input">
<input type="text" placeholder="Enter Command" id="command-box">
<input type="submit" style="display: none">
</form>
I made the submit invisible so you could press enter and it would submit the form. Here is the JavaScript I'm using:
function changeStyle(sheet) {
document.getElementById('specific-sheet').setAttribute('href', sheet);
}
var command = document.getElementById('command-input');
if(command.value=="windows"){
changeStyle('../css/windows-xp.css');
}
I want to make it to where if I type "windows" into the command box and hit enter, it will change my stylesheet. The people on this website are smart, so I once again am asking for help. Thanks for contributing!
You will need to check with an event. Assuming this is in the plain tags; you can use the following:
var inputbox = document.getElementById('command-input');
function changeStyle(sheet) {
document.getElementById('specific-sheet').setAttribute('href', sheet);
}
inputbox.addEventListener('input', function (evt) {
if (this.value == 'windows'){
changeStyle('../css/windows-xp.css');
}
});
Edit:
you can do this as well. Change the event to "onsubmit" if you want enter key to trigger.
function changeStyle(sheet) {
document.getElementById('specific-sheet').setAttribute('href', sheet);
}
document.getElementById('command-input').addEventListener(
'keyup',
function(eve){
if (eve.target.value == 'windows'){
changeStyle('../css/windows-xp.css');
}
},
false
);
If you want to keep the changes even after the page refresh you might have to keep the file path in the localstorage and use that in dom load event.
Also, you really dont need to wrap this in a form tag. You can use a simple div and this is not triggered by a form submit.
You could create a function that you can call on form submission as explained here at https://www.w3schools.com/jsref/event_onsubmit.asp.
<form onsubmit="myFunction()">
Enter name: <input type="text">
<input type="submit">
</form>
<script>
function myFunction() {
var command = document.getElementById('command-input');
if(command.value=="windows"){
changeStyle('../css/windows-xp.css');
}
}
</script>

How add name input submit() jQuery

I have a JavaScript that changes the attribute of the input button to "disabled", so the user don't submit the page twice.
// Disables multiple submit
function disableSubmit (btn, submitForm) {
// Sets button as disabled, changes class and cursor
$(btn).attr("disabled", true);
$(btn).toggleClass("disabled alt2");
$(btn).css('cursor', 'initial');
$(btn).attr("value", "Sender...");
// Submits form
$(submitForm).submit();
}
// Disables submit for order form
$("#send-order").click(function () {
return disableSubmit(this, "#order");
});
The problem is that I need to track the name of the button submitting the page so I can handle it in my Django view.py file.
HTML
<input value="Send bestilling" id="foo" name="send-order" type="submit" class="button alt2">
View.py
request.POST.get("send-order", False)
But if I use my script to submit the page, I can't get the name of the input submitting the page. Is there any way to set a name for the button submitting the page in my script?
I tried this but didn't work:
$(submitForm).submit().attr("name", "send-order");
Solution
I had to change the code inside views.py in order to make this work.
you can use preventdefault or return false
$("#send-order").click(function (event) {
event.preventDefault();
return disableSubmit(this, "#order");
});
Or
<input id="send-order" value="Send" type="submit" onclick="disableSubmit(this, '#order');return false" />
One way you can do this is by creating a hidden input on your form, with a name of its own. Something like below.
<input type="hidden" name="buttonName" id="buttonName" />
Then, in your disableSubmit function, make it set the value of that input before submitting.
$(submitForm)
.find("input[name=buttonName]")
.attr("value",
$(btn).attr("name")
);
From there, you can just retrieve the "buttonName" value in your View.py.

How can I keep focus on a overlay popup after submitting a form?

I have an overlay popup with a form inside. The form has a button and a textbox (imagine something like the FB Like and Comment box). Every interaction with the form triggers a MySQL DB Insert called through a PHP function. The problem is that after having clicked on the button or commented (and pressing enter key on the keyboard), the overlay disappears and the main page is refreshed. I don't want this to happen and I want to keep the focus on the popup. How can I do that?
Here's some code:
<div id="LikeAndComment">
<form name="formLAC" method="post" action="">
<div id="containerLike">
<button type="submit" id="likeit" value="FALSE" onClick="{vote(); keepFocus();}">
<img src="images/implike_BUTTON.jpg" "/>
</button>
</div>
<div id="containerComment">
Commenta: <input type="text" class="input" id="comment" onkeydown="if (event.keyCode == 13) { this.form.submit(); keepfocus(); return false; }"></input>
</div>
</form>
</div>
And here's the code of the keepFocus function:
function keepFocus() {
$('.formLAC').focus();
};
When you submit form as default without prevent form submit and using ajax, The browser will generate a new request and redirct you to the action url that you defined.
What you ask is to submit the form without redirect the page.
The ideal solution is to use ajax.
You can catch the submit-form event and prevent the default action.
then you have to handle it with you own code, In this case the ajax function.
An example how to send form with ajax you can see on this post with nice answer:
link to how make form submit with ajax

Categories

Resources