I'm working on a project. I'm trying to make my code so that when a user submits an option from a dropdown menu, if the user selects and submits the default ("Select a genre"), the form is not submitted and the page is not refreshed. Following is my Javascript code:
<script>
var menu = document.getElementById("submit");
menu.addEventListener("click", function() {
if (document.getElementById("dropdown").value == 'nothing')
{
return false;
}
});
</script
This is nested inside a head tag.
Following is my HTML code for the form:
<div>
<form method="POST">
<select id="dropdown" name="genre">
<option value="nothing">Select a genre</option>
<option value="rock">Rock</option>
</select>
<br/>
<br/>
<input id="submit" type="submit"/>
</form>
</div>
The javascript doesn't seem to work, since even when I submit the form while selecting the "Select a genre" option, my form is still submitted, and the python code does work on the value 'nothing', which gives errors.
EDIT: Upon adding further functionality to my project by adding more javascript code, the javascript code again didn't work. I used google chrome's developer tools and stumbled upon this error which seems to be related to why the code isn't working:
Uncaught TypeError: $(...).addEventListener is not a function
at (index):18
Try event.preventDefault():
var menu = document.getElementById("submit");
menu.addEventListener("click", function(event) {
if (document.getElementById("dropdown").value == 'nothing')
{
event.preventDefault();
}
});
<div>
<form method="POST">
<select id="dropdown" name="genre">
<option value="nothing">Select a genre</option>
<option value="rock">Rock</option>
</select>
<br/>
<br/>
<input id="submit" type="submit"/>
</form>
</div>
It is just a declaration of Code if you don't bind to $( document ).ready() or make it as self-invoking function.
First solution:
$( document ).ready(functino(){
var menu = document.getElementById("submit");
menu.addEventListener("click", function() {
if (document.getElementById("dropdown").value == 'nothing')
{
return false;
}
});
});
Another Solution:
(function(){
var menu = document.getElementById("submit");
menu.addEventListener("click", function() {
if (document.getElementById("dropdown").value == 'nothing')
{
return false;
}
});
}());
Related
I want the to get the required in the html page if none is selected.
function validation() {
var country = getElementById("country");
if (country.value = "") {
documnet.getElementById("countryy").innerHTML = "Required";
return false;
} else
return true;
}
<form onsubmit="return validation();">
<select id="country"><span id="countryy"></span>
</select><br>
<input type="submit" name="Submit" value="Submit">
</form>
Why The Validation is not working for the provided html/ js code. I want the to get the required in the html page if none is selected. I am new to js learning.
Several issues
Spelling mistake in the document.getElementById
missing document on the other document.getElementById
No preventDefault which will submit the form if any JS errors
= is assignment - you need == or === to compare
span needs to be outside the select
You did not use value="Default" in the "NONE" options
It is not recommended to have inline event handlers. Here is a better version
Note I added a class to toggle the required in case the user changes the select to conform
window.addEventListener("load", function() {
const errorSpan = document.getElementById("countryy"); // cache the elements
const country = document.getElementById("country");
document.getElementById("myForm").addEventListener("submit", function(e) {
const val = country.value; // get the value
if (val === "") {
e.preventDefault(); // stop submit
}
errorSpan.classList.toggle("hide",val); // hide if value
})
country.addEventListener("change",function() { // if user changes the select
errorSpan.classList.toggle("hide",this.val); // hide if value
})
})
.hide { display : none; }
<form id="myForm">
<select id="country">
<option value="">NONE</option>
<option value="ABDUL">ABDUL</option>
<option value="SULE">SULE</option>
</select> <span id="countryy" class="hide">Required</span><br>
<input type="submit" name="Submit" value="Submit">
</form>
HOWEVER you could remove all the script and just add required attribute to the select and keep the empty default
<form id="myForm">
<select id="country" required>
<option value="">NONE</option>
<option value="ABDUL">ABDUL</option>
<option value="SULE">SULE</option>
</select><span id="countryy"></span><br>
<input type="submit" name="Submit" value="Submit">
</form>
Use required attribute in the select tag. It will considered in html 5 validation.
https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_select_required
I want to use an <input type="submit"> button as a link to open another webpage in the current tab. I am using the attribute multiple but I want to display the select menu like this
Here is my HTML:
<form id="link">
<select multiple="multiple" >
<option value="" disabled selected hidden>Моля изберете</option>
<option value="volvo">Кардиолог</option>
<option value="gastro.html" target="_blank">Гастроентеролог</option>
<option value="mercedes">Ортопед</option>
<option value="audi">Дерматолог</option>
<option value="audi">Уролог</option>
</select >
<div class="btn">
<button class="SubmitButton" type="submit" name="SUBMITBUTTON" value="Submit" onsubmit="return validateForm();" >Търси</button>
</div>
</form>
And here is my Javascript and jQuery:
$('#link').on('submit', function (e) {
// e.preventDefault();
var $form = $(this),
$select = $form.find('select'),
links = $select.val();
if (links.length > 0) {
for (i in links) {
link = links[i];
window.open(link);
}
}
});
How do I rewrite my code so that when the user submits the form, the new webpage opens in the current tab instead of a new window?
You can't change the behaviour of window.open. It's a user preference and browsing context: https://developer.mozilla.org/en-US/docs/Web/API/Window/open
But you could change your code. If it's an API, instead of open a new link you could just fetch this link and display the result somewhere.
But since it isn't look like an API... you could use some AJAX technologies to get its content and put it in an element at your current page (but it's look like a web at 2010).
Trying to guess your question the answer should be:
Do a preventDefault and then disable the submit Button. Now you can open your "tab".
In this way, users can submit only once and cannot open new pages
Your Problem
In your Javascript, you used window.open(link) to open the link. But this Javascript function opens URLs in a new window. You want the URL to open in the current tab, not to open in a new window or new tab.
My Solution
Replace this line in your code:
window.location = link;
With this line:
window.location.href = link;
This Javascript function stimulates clicking on a link.
Or simply replace your Javascript with the Javascript in my code snippet. I’ve also changed the .on(‘submit’, function(e) {…}); function, which is outdated, with .submit(function(e) {…}); which is the preferred method.
<form id="link">
<select multiple="multiple" >
<option value="" disabled selected hidden>Моля изберете</option>
<option value="volvo">Кардиолог</option>
<option value="gastro.html" target="_blank">Гастроентеролог</option>
<option value="mercedes">Ортопед</option>
<option value="audi">Дерматолог</option>
<option value="audi">Уролог</option>
</select >
<div class="btn">
<button class="SubmitButton" type="submit" name="SUBMITBUTTON" value="Submit" onsubmit="return validateForm();" >Търси</button>
</div>
</form>
$('#link').submit(function (e) {
// e.preventDefault();
var $form = $(this),
$select = $form.find('select'),
links = $select.val();
if (links.length > 0) {
for (i in links) {
link = links[i];
window.location = link;
}
}
});
I have a large form that I want to monitor for changes. I found example code for that in this post. When I run the code as posted, it works fine. But my form is using Ajax and it doesn't work for some reason. Here's my jsfiddle. I added a second monitor near the bottom but it isn't working either.
When the monitoring code is in the doc ready function, even the first "hello" update doesn't work. But this may be something to do with jsfiddle since I can get past that point locally. But even then, the origForm data is not seen more than once because, I think, the doc ready function is only called the one time when Ajax loads it.
Is there a way to monitor all of the fields when using Ajax?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="saved_form"></div>
<div id="changed"></div>
<div id="showform"></div>
<script>
$(document).ready(function() {
ShowForm();
$("#saved_form").text("hello");
var $form = $("form"),
origForm = $form.serialize();
$("#saved_form").text(origForm);
$("form :input").on("change input", function() {
$("#changed").text("A change was made");
});
});
function ShowForm () {
$.ajax({
url: 'ajax3.php',
success: function(data) {
$("#showform").html(`
<form>
<div>
<textarea name="description" cols="30" rows="3"></textarea>
</div>
<div>Username: <input type="text" name="username" /></div>
<div>
Type:
<select name="type">
<option value="1">Option 1</option>
<option value="2" selected>Option 2</option>
<option value="3">Option 3</option>
</select>
</div>
<div>
Status: <input type="checkbox" name="status" value="1" /> 1
<input type="checkbox" name="status" value="2" /> 2
</div>
</form>
`);
}
});
};
var $form2 = $("form"),
origForm2 = $form2.serialize();
$("#saved_form").text(origForm2);
$("form :input").on("change input", function() {
$("#changed").text("A change was made");
});
</script>
You are dynamically adding the form to your page. The selector will not pick up the change event. Also the event and selector in the on method are defined properly. more information about the on method can be found here http://api.jquery.com/on/
Try this:
$(document).on("change", "input, textarea", function() {
$("#changed").text("A change was made");
});
You can use .promise() after using .html() to render your form. This callback is launched right after form has been populated. Then you can use $("#showform form :input") to monitor events just on this eactly form. It costs less in performance than doing with $(document).on(...)
In your code:
function ShowForm () {
$.ajax({
url: 'test',
success: function(data) {
$("#showform").html(`
// <--- All your previous html -->
`).promise().done(function(){
// <--- Execute your monitor after rendering new form -->
$("#showform form :input").on("change input", function() { $("#changed").text("A change was made");
});
});
}
});
};
Look at the updated jsfiddle
To know more about .promise() here-jquery-promises
How I can make the selected choice still visible until I re-choose another one?The list may contain more than 10 options
=====
<form method="get" action="Chairman.php" >
<select name="courses" id="courses" class="styled-select" >
<option value="courses"><--Courses--></option>
<option value="PHYS220">Physics for Engineers</option>
<option value="MATH210">Calculus II</option>
<option value="MATH225">Linear Algebra with Applications</option>
</select>
<input type="submit" value="Search Instructor"
onClick="checkDropdown()"></input>
<div id="error" style="color:red"></div>
=====
Also when I am trying to validate the select list,The error is displayed and then quickly it disappears
<script>
function checkDropdown () {
var courses = document.getElementById('courses');
if(courses.value==="courses") {
document.getElementById('error').innerHTML="PLEASE selecttt";
return false;
}
}
</script>
The select is reset and the error disappears because the form is still posted. The value that you return from the function doesn't stop the submission.
You should use the onsubmit event on the form instead of onclick on the button. Use return in the event code to convey the value from the function back to the event:
<form method="get" action="Chairman.php" onsubmit="return checkDropdown()">
My code is as follows:
<!DOCTYPE html>
<html>
<body>
<script>
function tab()
{
current=document.getElementById("test");
next=document.getElementById("run");
if(current.value!="-1")
{
next.focus()
}
}
</script>
<select id="test" onchange="tab()">
<option value="-1">--select--</option>
<option value="1" >TEST</option>
<option value="2">RUN</option>
</select>
<input type="text" name="run"/>
</body>
</html>
Definition: I have a dropdown which is having four values. If I change one value to another value in the dropdown it autotab to the textbox. As per my code, it is working fine.
But the issue is when I select 1st value in the dropdown then the autotab is working and again I select the same value from the dropdown (autotab is not working). I know that the problem is in the event. There is no change so the event won't fire. Please help me to rectify the issue.
There is no element with id run, which is being referenced by:
document.getElementById("run");
You probably intended to write:
<input type="text" name="run" id="run"/>
Use onBlur() instead of onchange().
The onBlur event is fired when you have moved away from an object without necessarily having changed its value.
The onChange event is only called when you have changed the value of the field.
please have a lookinto this to know about events
Try using mouseup & keyup event as a work around:
var current = document.getElementById("test");
var next = document.getElementById("run");
var open = false; //drop-down closed
var watchOpen = function() {
open = !open; //inverse flag to identify state of drop-down
};
var tab = function() {
if (!open && current.value !== "-1") {
next.focus();
}
};
<select id="test" onmouseup="watchOpen();tab();" onkeyup="watchOpen();tab();">
<option value="-1">--select--</option>
<option value="1">TEST</option>
<option value="2">RUN</option>
</select>
<input type="text" id="run" /><!-- replaced name with id -->
try to use onBlur() .It will solve the problem
I think this is possible with html5
onselect
Try this :
<!DOCTYPE html>
<html>
<body>
<select id="test" onchange="tab()">
<option value="-1">--select--</option>
<option value="1">TEST</option>
<option value="2">RUN</option>
</select>
<input type="text" name="run" id="run" />
<script type="text/javascript">
function tab() {
current = document.getElementById("test");
next = document.getElementById("run");
if (current.value != "-1") {
next.focus();
next.value = current.options[current.selectedIndex].text;
} else {
next.value = "";
}
}
</script>
</body>
</html>