This is what I want to do: The user has to complete a form and if the quantity of items is odd a modal should pop up with a message, if the quantity is even then the form should be submitted and no modal should pop up. I am trying to do it in JavaScript using AJAX but with no success. I am new into JavaScript. Any help and ideas are welcome. This is the code I have so far.
//this is the submit button,
//which if is pressed and the number is odd should trigger the modal
<input id="myButton" type="submit" class="button_submit" value="Submit">
<input type="submit" id='myButton' class="button_continue" value="Submit anyway !">
<a id='button_back' class="button_back">Take me back !</a>
//these 2 buttons are on the modal, they work
<script>
var xhr = new XMLHttpRequest();
var modal = document.getElementById('modal');
var button = document.getElementById('myButton')
var page = document.getElementById('content')
var back = document.getElementById('button_back')
var message = document.getElementById('warning_msg')
var item = parseInt(qty_item) (this is the input)
xhr.onload = function() {
if (item % 2 != 0) {
button.onclick = function() {
modal.style.display = 'flex';
message.innerHTML='You cannot have an odd number.';
console.log('Log in 1');
}
}
} else {
button.onclick = function() {
modal.style.display = 'none';
console.log('Log in 2');
}
}
xhr.open("GET", "/new");
xhr.responseType = "text";
console.log('About to send')
xhr.send();
console.log("This has worked")
You should move the odd/even condition into the button click event as below:
xhr.onload = function() {
button.onclick = function() {
if (item % 2 !== 0) {
modal.style.display = 'flex';
message.innerHTML = 'You cannot have an odd number.';
console.log('Log in 1');
}
else {
modal.style.display = 'none';
console.log('Log in 2');
}
}
}
Moreover, change the id
attribute of the 2nd button, because id
has to be unique
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.