Reputation: 21
I'm designing a website and I need the below function to stop when one Input value is missing and display the error message. My HTML code for the form:
<form action="http://localhost/qurantest/" method="get" target="_blank" id="my-form">
<input type="text" name="reference-number" id="reference-number" value="" class="6u 12u$(xsmall)" placeholder="enter chapter"/>
<input type="text" name="reference-number" id="reference-number2" value="" placeholder="enter verse"/>
<br>
<input type="submit" value="GO" class="button big special" />
</form>
The JavaScript function is;
<script type="text/javascript">
var form = document.querySelector('#my-form'),
text_field = document.querySelector('#reference-number');
text_field2 = document.querySelector('#reference-number2');
function submitHandler(){
// build the new url and open a new window
var url = form.action + text_field.value + '/' + text_field2.value;
window.open(url);
// prevent the form from being submitted because we already
// called the request in a new window
return false;
}
// attach custom submit handler
form.onsubmit = submitHandler;
</script>
What I want is: To stop the function and display an error message when 1 of the two "inputs" (text_fields) is empty. Also, I want to assign maximum values for each input. (In my case I want the 1st input field to contain only numbers between 1-114 and the 2nd input field to contain only numbers from 2-286), and this specific function opens in a new window as the above code suggests, I want the function to open in the current window itself. How can I do this is JavaScript? I'm new to JS so any help would be appreciated. Thanks in Advance!!
Upvotes: 0
Views: 507
Reputation: 49
Check this one.
<script type="text/javascript">
var form = document.querySelector('#my-form');
var text_field = document.querySelector('#reference-number');
var text_field2 = document.querySelector('#reference-number2');
function submitHandler(){
if(!text_field.value || !text_field2.value) {
console.log("error message here");
return;
}
var url = `${form.action}${text_field.value}/${text_field2.value}`;
window.open(url);
return;
}
form.onsubmit = submitHandler;
</script>
Upvotes: 1
Reputation: 328
<script type="text/javascript">
var form = document.querySelector('#my-form'),
text_field = document.querySelector('#reference-number');
text_field2 = document.querySelector('#reference-number2');
function submitHandler(){
// checks values
if(text_field.value == "" || text_field2.value == "") {
alert("Message");
return false;
}
// build the new url and open a new window
var url = form.action + text_field.value + '/' + text_field2.value;
window.open(url);
// prevent the form from being submitted because we already
// called the request in a new window
return false;
}
// attach custom submit handler
form.onsubmit = submitHandler;
</script>
Upvotes: 0