I'm trying do something like this:
Initially, the user has button "Edit booking", but after clicking on it something activates and button becomes a submit button. When the user enters his info and clicks submit, this data goes to servlet.
It works partially, but the problem is that when the button changes, I don't have a moment when the user can enter their data.
Here is my current code:
<c:if test="${booking.status == 'Checking'}">
<form name="myForm" id="myForm">
<input type="button" value="Edit booking" id="editButton"
onclick="activate(); changeButton();">
</form>
<script>
function activate() {
var editButton = document.getElementById("editButton");
if (editButton.value == "Edit booking") {
document.getElementById("bookingDate").disabled = false;
document.getElementById("returnDate").disabled = false;
editButton.setAttribute('type','submit');
}
else {
document.getElementById(editButton).action = "/BookingUpdate";
document.getElementById("bookingDate").disabled = true;
document.getElementById("returnDate").disabled = true;
}
}
</script>
<script>
function changeButton() {
var editButton = document.getElementById("editButton");
if (editButton.value == "Edit booking") {
editButton.value = "Submit";
}
else {
editButton.value = "Edit booking";
editButton.setAttribute('type', 'button');
}
}
</script>
</c:if>
Actually, you can submit a form data by either using a submit button or calling a submit function document.getElementById("myForm").submit()directly in javascript code.
thus, you can try something like below:
<form name="myForm" id="myForm">
<input type="button" value="Edit booking" id="smartButton" onclick="doSomethingSmart();">
</form>
<script>
var smartButton = document.getElementById("smartButton");
var myForm = document.getElementById("myForm");
function doSomethingSmart() {
if(smartButton.value == "Edit booking") { // we gonna edit booking
document.getElementById("bookingDate").disabled = false;
document.getElementById("returnDate").disabled = false;
smartButton.value = "submit"; // let it in disguise as submit button
}
else { // we gonna submit
if( isUserInputValied() ) {
myForm.submit(); // submiiiiiiiiiiiiiiiiiit !
// restore everything as if nothing happened
document.getElementById("bookingDate").disabled = true;
document.getElementById("returnDate").disabled = true;
smartButton.value="Edit Booking";
}
else {
alert("please fill your form correctly!");
}
}
}
function isUserInputValid() {
// check whether the user input is valid
}
</script>
You need to prevent the default event if it's in edit mode so that it won't submit the form. You can always have your button type as submit no need to change it to button.
This should work:
var button = document.getElementById('editButton');
button.addEventListener('click', toggleButton);
function toggleButton(e){
var isEdit = button.value === 'Edit booking';
if(isEdit){
document.getElementById("bookingDate").disabled = false;
document.getElementById("returnDate").disabled = false;
button.value = 'Submit';
e.preventDefault();
}
}
Related
I have a form which contain elements (checkboxes) that will be produced using JavaScript and I want to check if at least one of them is checked. Also, I have a few inputs that I want to check if at least one of them has value. The initial problem was The code I wrote displayed the error message but immediately submits the form. I can't use server side validation here because these items are created through JS. and I'm not sure if I can use server side validation to check if at least one input field has value.
For this problem I tried using e.preventDefault(); , it stops the form from submitting if there is no value or checkbox not checked but if there was a value it will still not submit the form
This the code I tried
$(function () {
$("#SubmitForm-btn").click(function () {
$("#fupForm").submit(function (e) {
e.preventDefault();
var valid = true;
//here I'm checking if any of the input field has value.
$('#dataTable tbody tr td input[type=text]').each(function () {
var text_value = $(this).val();
if (!hasValue(text_value)) {
valid = false;
$("#tableEmpty").html("Please Choose a Service");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
})
//here I'm checking if any of the checkbox is checked.
$('.check').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#Person_errorMSG").html("Please choose a person");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
//here I'm checking if any of the checkbox is checked.
$('.Fromcheck').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#From_errorMSG").html("Please choose a City");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
//here I'm checking if any of the checkbox is checked.
$('.Tocheck').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#To_errorMSG").html("Please choose a To city");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
});
});
});
You should prevent the button click event, instead of the form submit action.
Please refer the following sample code:
In the View page, we have a mainform.
<form id="mainform" asp-action="AddAttribute">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="AttributeId" class="control-label"></label>
<input asp-for="AttributeId" class="form-control" />
<span asp-validation-for="AttributeId" class="text-danger"></span>
</div>
...
<div class="form-group">
Is Submit <input type="checkbox" class="isSubmit" />
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" id="SubmitForm-btn" />
</div>
</form>
At the end of the above page, add the following script:
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
$(function () {
$("#SubmitForm-btn").click(function () {
event.preventDefault(); //prevent the default submit action.
//check if the checkbox is checked or not.
var ischecked = $(".isSubmit").last().is(":checked");
if (ischecked) {
//alert("Checked");
//if the cleckbox checked, submit the form.
$("#mainform").submit();
}
else {
//alert("Unchecked");
//show notification message. and the form will not submit.
}
});
});
</script>
}
The result as below:
Here is my sample code:
<button onClick="CheckData()" type="submit">
I have some conditions in CheckData function:
if (5<6) {
warning = "sure?";
} else if (5>3) {
warning = "really?";
} else {
warning = '';
}
Then I check:
if (warning.length>0) {
return confirm(warning);
} else {
return true; //also tried false
}
So I need the confirm dialog for the first two conditions, otherwise, I don't want the dialog to be displayed.
Now, when one of the first two conditions are met, the confirm dialog pops up, but when I click on cancel, it still submits the form.
Any suggestions?
PS: This code is a demo and different from the real one. But the concept is the same.
You can pass in the event Object to the CheckData function and prevent the default action if the confirm returns false with event.preventDefault().
<form>
<button onClick="CheckData(event)" type="submit">Submit</button>
</form>
<script>
function CheckData(e){
var warning;
if (5<6) {
warning = "sure?";
} else if (5>3) {
warning = "really?";
} else {
warning = '';
}
if (warning.length>0) {
var con = confirm(warning);
if(con){
return true;
} else {
e.preventDefault();
return false;
}
} else {
return true;
}
}
</script>
You can also return the result of CheckData so the default action will be prevented if it returns false.
<form>
<button onClick="return CheckData()" type="submit">Submit</button>
</form>
<script>
function CheckData(){
var warning;
if (5<6) {
warning = "sure?";
} else if (5>3) {
warning = "really?";
} else {
warning = '';
}
if (warning.length>0) {
var con = confirm(warning);
return con;
} else {
return true;
}
}
</script>
Change your HTML to this:
<form onsubmit="return CheckData()">
<button type="submit" />
...
</form>
Explanation:
The onsubmit event handler is called when the form is submitted.
When the event handler returns false the submission is aborted.
I have a problem with my js script because for both button will open te same site 1. I don't know why?
Could somebody help me to resolve this problem?
$('#trackAndTraceForm').submit(function(event) {
var val = $('input[name="numer"]', this).val();
elementClicked = $(event.target);
var typeBtn = elementClicked.attr('name');
if (typeBtn == 'spr') {
if (val.substring(0, 1) != '0') {
//console.log('nie zero');
var action = 'http://92.43.115.24:8080/ApolloWebBooking/WebBooking/StatusyPrzesylki.aspx';
$(this).attr('action', action);
} else {
var action = 'http://apollo.loxx.pl:8080/ApolloWebBooking/WebBooking/StatusyPrzesylki.aspx';
$(this).attr('action', action);
}
} else if (typeBtn == 'pod') {
var action = 'http://www.loxx.pl/loxx_it/loxxwarpod.php';
$(this).attr('action', action);
} else {
//do nothing;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="trackAndTraceForm" target="_blank" class="form-horizontal" enctype="application/x-www-form-urlencoded" method="get" action="http://apollo.loxx.pl:8080/ApolloWebBooking/WebBooking/StatusyPrzesylki.aspx">
<span>Track and Trace:</span>
<input type="text" value="" name="numer" placeholder="Numer listu przewozowego" />
<input type="submit" name="spr" class="btn btn-sm btn-primary" value="Sprawdz" />
<input type="submit" name="pod" class="btn btn-sm btn-primary" value="POD" />
</form>
If I click POD button action is the same like for Sprawdz with url
http://apollo.loxx.pl:8080/ApolloWebBooking/WebBooking/StatusyPrzesylki.aspx?numer=0317037128&pod=POD
You need to prevent the original event from triggering the default submit action. You do that by calling event.preventDefault();.
Here's what your code needs to look like:
$('#trackAndTraceForm').submit(function(event) {
event.preventDefault(); // <-- the important bit
// ...
if (typeBtn == 'spr') {
// ...
} else if (typeBtn == 'pod') {
// ...
}
});
Looks like you can't change the action attribute of the event after the submit event has been called.
What you need to do is to add event listeners to each of your buttons, change the action attribute and then submit the form:
function changeFormAction(newAction) {
$('#trackAndTraceForm').attr('action', newAction);
}
$('input[name="spr"]')
.click(function(e) {
e.preventDefault();
var value = $('input[name="numer"]').val();
var newAction = value.startsWith('0') ?
'http://apollo.loxx.pl:8080/ApolloWebBooking/WebBooking/StatusyPrzesylki.aspx' : 'http://92.43.115.24:8080/ApolloWebBooking/WebBooking/StatusyPrzesylki.aspx';
changeFormAction(newAction);
$('#trackAndTraceForm').submit();
}
$('input[name="pod"]')
.click(function(e) {
e.preventDefault();
changeFormAction('http://www.loxx.pl/loxx_it/loxxwarpod.php');
$('#trackAndTraceForm').submit();
}
Hi I'm using this script to prevent users from submitting specific blank form text input fields. Does a great job but I have 2 submit buttons within 1 form and I need this to work for only 1. Is there any way to make this code below apply to 1 specific button using the button id or name?
<script type="text/javascript">
$('form').on('submit', function () {
var thisForm = $(this);
var thisAlert = thisForm.data('alert');
var canSubmit = true;
thisForm.find('[data-alert]').each(function(i) {
var thisInput = $(this);
if ( !$.trim(thisInput.val()) ) {
thisAlert += '\n' + thisInput.data('alert');
canSubmit = false;
};
});
if( !canSubmit ) {
alert( thisAlert );
return false;
}
});
</script>
Your first line:
$('form').on('submit', function () {
will take all form elements in the document. You can change the 'form' part of that to the ID of the form element i.e.
$('#form1').on('submit', function () {
You have one form and two submit buttons which, by default, will both submit the form. To prevent one button from submitting, add a click handler that both prevents the default submit action and does whatever else you want that button to do.
HTML
<form id="form1">
<input type="text" value="something" />
<input id="submit1" type="submit" value="send" />
<input id="submit2" type="submit" value="ignore" />
</form>
JavaScript
$('#submit2').on('click', function (event) {
event.preventDefault();
// Form will not be submitted
// Do whatever you need to do when this button is clicked
});
$('form ').on('submit ', function () {
var thisForm = $(this);
var thisAlert = thisForm.data('alert');
var canSubmit = true;
thisForm.find(' [data - alert]').each(function (i) {
var thisInput = $(this);
if (!$.trim(thisInput.val())) {
thisAlert += '\n ' + thisInput.data('alert ');
canSubmit = false;
};
});
if (!canSubmit) {
alert(thisAlert);
return false;
}
});
Demo https://jsfiddle.net/BenjaminRay/ccuem4yy/
I have this code in my view
function Validate() {
if (document.getElementById('MandateName').value == "") {
var err = document.getElementById('MandateNameErr');
err.innerHTML = "Please enter a value for the Mandate Name";
err.style.display = "block";
return false;
}
else {
document.getElementById('MandateNameErr').style.display = "none";
}
if (document.getElementById('MandateDescription').value == "") {
var err = document.getElementById('MandateDescriptionErr');
err.innerHTML = "Please enter a value for the Mandate Description";
err.style.display = "block";
return false;
}
else {
document.getElementById('MandateDescriptionErr').style.display = "none";
}
return true;
}
and I have on submit button I am validating before submiting?
<button name="Submit" onclick="Validate()" >Add Variables to Mandate</button>
I called Validate function but its showing me if I am not entering anything on the text box if I click Button its showing me my validation message but same time its going to my view and throwing me the message?
even I put the return false; its not working is that something I am doing wrong?
You need to put return in the onclick, like this:
<button name="Submit" onclick="return Validate()" >Add Variables to Mandate</button>
Otherwise you're executing the validation...but not really caring about the result.