How to validate bootstrap multiselect dropdown using jquery - javascript

I am trying to validate Bootstrap multiselect dropdown using the code given below, the form is getting validated but i did'nt get the proper output, the
validation message is above the selectbox and the message gets multiplied when
clicking on the submit button and after selecting option the message did'nt gets removed. Please help to solve my problem.
<script type="text/javascript">
$(document).ready(function() {
$.validator.addMethod("needsSelection", function (value, element) {
var count = $(element).find('option:selected').length;
return count > 0;
});
$.validator.messages.needsSelection = 'Select Atleast One College';
$("#User").validate({
rules: {
'college[]': {
needsSelection: true
}
},
}
});
$("#submit").click(function(e) {
var isvalidate=$("#User").valid();
if(isvalidate=="true")
{
}
else
{
$("#User").submit();
}
});
});
<form id="User" name="User" method="post" enctype="multipart/form-data" action="index">
<select data-placeholder="Choose College Name" name="college[]" class="chosen-select" id="college" multiple tabindex="4">
<option value=""></option>
<option value="1">abc</option>
<option value="2">abc1</option>
</select>
<a id="submit">Submit</a>
</form>

This is not a direct answer to your question, but may provide a solution to your problem.
First, change the anchor tag to a button -- because anchor tags have built-in navigation behaviour that you must counter (event.preventDefault()) and therefore add needless complexity. How about a button (input or button tags) or a div tag, or a p?)
Next, a simpler structure to evaluating your form:
jsFiddle Demo
HTML: (just changed your anchor submit button to:
<input id="dosubmit" type="submit" value="Submit" />
Note: do not use "submit" as the id for a submit button, as that is a reserved keyword
javascript/jQuery:
$('#User').submit(function(e){
var col = $('#college').val();
if ( col==null || col=='' || col=='Please choose one:' ){
$('#college').css('background','yellow').focus();
return false;
}else{
$('#college').css('background','transparent');
alert('Form submitted');
//continue to submit the form - but not now
return false;
}
});
Please consider this verification script for your project.

This is not an answer to your question but I will advise you and encourage you to use a server-side validation together.
Your data should be validate and as needed sanitzed on the php file that receives the ajax call.
If something is going wrong there, the response will always be passed back to your form giving your users the needed feedback.
You can find many examples on the internet of how to do this.
See here an example: https://scotch.io/tutorials/submitting-ajax-forms-with-jquery
So to recap: Dont't do client-side validation!!

Related

how do i trigger a button with the enter key in java script?/ how to give text box and search button an ID?

Sorry i know this question has been asked and answered before but i can't seem to implement it into my code. very new to programming and struggling quite a bit.
Pretty simple stuff here i have a search bar and a search button. What i am trying to do is instead of having to physically click the search button to search for what i want, i would like to have the ability to be able to click the enter key which could search as well. Here is the code for the search bar and button.
Easy stuff.
<div class="ui-widget"> <!-- only for css purposes-->
<input id="search"> <!-- for the search box-->
<button type="button" onclick="searchresult()">Search</button> <!-- search button-->
</div>
So at the moment when you click the search button it will activate the javascript function i have which is:
function searchresult() {
//find the result
}
which in turn will find the result you want. deadly stuff.
I haven't included the code which is inside the javascript function as we don't need it for this question and its quite lengthy.
so basically i want the enter key to be able to activate the searchresult javascript function the same way the search button does.
I am aware that you can use jQuery keypress() Method to do this. and here is the code which can be used to do what i am wondering but i just don't know how to implement it into what i have:
$("#id_of_textbox").keyup(function(event){
if(event.keyCode == 13){
$("#id_of_button").click();
}
});
I am aware of the id attribute which is used in HTML coding as well but i don't know how i would go about correctly assigning the search button and text box an id each which then i could use in the code i have just above which then in turn would allow me to use the enter key as search as well.
So if anyone could just show me how i could use the jQuery code i found to solve my question that would be brilliant. Completely open to any other suggestions about how i would go about it either.
Thank you everyone for your time and attention!
Use the following code (explanation below):
function searchresult() {
console.log('searching');
//find the result
}
$("#search").keyup(function(event) {
if (event.keyCode == 13) {
$("#searchButton").click();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ui-widget">
<input id="search">
<button type="button" id="searchButton" onclick="searchresult()">Search</button>
</div>
What this does is it will hook up an event to the input box with the id search and whenver it receives a keyup (key release) event, it will check if it is the Enter key and, if so, fire the click event of the button with id searchButton (I added that id as an example). Your search button's click event is hooked up to the searchResult() function, which is in turn called from that.
If you need more information on how event handling works in jQuery, check out jQuery's Handling Events page.
You really should consider using a form.
function search_function(search_terms){
// Do your search action here
alert(search_terms);
};
$(function(){
$("#search").on("submit", function(e){
search_function($("#search_terms").val());
e.preventDefault(); // Prevents submitting in most browsers
return false; // Prevents submitting in some other browsers
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='search'>
<input type='text' id='search_terms' placeholder='Search' />
<button>Search</button>
</form>
Or here is an example in pure JS
function search_function(search_terms){
// Do your search action here
alert(search_terms);
};
document.addEventListener("DOMContentLoaded", function(){
document.getElementById("search")
.addEventListener("submit", function(e){
search_function(document.getElementById("search_terms").value);
e.preventDefault(); // Prevents submitting in most browsers
return false; // Prevents submitting in some other browsers
});
}, false);
<form id='search'>
<input type='text' id='search_terms' placeholder='Search' />
<button>Search</button>
</form>
You can assign the id to your search button :
<button type="button" onclick="searchresult()" id="search_key">Search</button>
Then you can trigger the click action on button using jQuery#trigger
JS :
$("#id_of_textbox").keyup(function(event) {
if (event.keyCode == 13) {
$("#search_key").trigger('click');
}
})
$('#search").change(function() {
searchResult();
});
Don't even bother with looking for the "enter" key; just watch for the input value to change (which would happen upon pressing enter, or blurring the field).
You can use a form and it's onsubmit event since you want enter key and submit click to do the same thing.
<form action="" method="" onsubmit="searchresult(this);">
<input type="text" name="query" />
<input type="submit" value="Search" />
</form>
But don't forget to use event.preventDefault() or return false.

Change form action on drop down selection

So I've got myself a form here shown below; I'm trying to change the form's action link based on the selection. However it's not really working for me.
<form action="">
<select id="location">
<option value="http://www.google.com/php:id=384733">New York</option>
<option value="http://www.google.com/php:id=384734">Georgia</option>
</select>
<input type="submit" value="Submit">
</form>
$("#location").change(function() {
var action = $(this).val();
$("form").attr("action")};
});
)};
There's more then just the two states, I'll have all states but for this example I've listed two. the value would be the url with different ID numbers as shown above.
In the end, if I selected New York the action in the form code would get updated and show something similar to this;
<form action="http://www.google.com/php:id=384733">
You're almost there, just a few syntax errors, and you're never setting the attribute
$("#location").on('change', function() {
$(this.form).attr("action", this.value);
});
There seems you have a typo in your javascript, check this:
$("#location").change(function() {
var action = $(this).val();
$("form").attr("action",action);
});

How can I do simple validation of a dropdown list?

I've made a 'question-answer form' in HTML and linked it with Javascript so that people could answer with a specific number. Here is the sample of my code:
HTML code:
<p>Question</p>
<p>1)"ans1"</p>
<p>2)"ans2"</p>
<p>3)"ans3"</p>
<p>4)"ans4"</p>
<form method="POST" name="CorrectForm"
onSubmit="checkCorrect(document.CorrectForm.numCorrect.value); return false;">
<input type="text" name="numCorrect" id="numCorrect">
<input type="Submit" name="Submit">
</form>
JavaScript:
var correctnumber = 1;
var errormessage = "blabla";
function checkTrue (numTrue){
if (numCorrect == correctNumber){
alert("Correct")
}else{
alert(errormessage);
}
}
Now what I want is to let people choose an answer from a dropdown list. So I want the answers to be checked when the submit button is pressed.
So, HTML looks like
<p>Question</p>
<select>
<option value="ans1">ans1</option>
<option value="ans2">ans2</option>
<option value="ans3">ans3</option>
<option value="ans4">ans4</option>
</select>
So now I'm need of the JS part.
I apologize if this question has been asked a million times before, as I tried searching for a solution but didn't find one.
Thanks in advance!
Instead of creating a function that validates just the input number, you can create a function that validates the full form. See this example:
<!DOCTYPE html>
<html>
<head>
<title>Validation test</title>
<script>
var rightAnswer = 3;
function checkAnswer(form) {
if (parseInt(form.elements["answer"].value) == rightAnswer) {
alert("Correct");
} else {
alert("Wrong");
}
return false;
}
</script>
</head>
<body>
<form method="POST" onsubmit="checkAnswer(this); return false;">
<p>Question:</p>
<select name="answer">
<option value="1">ans1</option>
<option value="2">ans2</option>
<option value="3">ans3</option>
<option value="4">ans4</option>
</select>
<input type="submit">
</form>
</body>
</html>
Some remarks:
In the code for the event onsubmit="", you can use the keywork this to refer to the form itself, and pass it to the checkAnswer() function.
When you have the variable form that points to your HTML form, you can retrieve its fields through form.elements["NAME"], where NAME matches the attribute name="" in the HTML tag. This works for all controls, select, button, input, with the exception of <input type="image">.
See MDN about this, it contains good reference about every object in the HTML DOM, in particular <select>.
You might still need to convert the value to an integer to be able to compare it to your right answer, that's the reason for parseInt.
This approach can be generalized: what you want to do is equivalent to form validation, you can find online plenty of libraries and tutorials that explain in detail how to do it; there are also many answers, if you know what to look for.

Javascript onclick confirm not working with "required" tag HTML

I have a <select> list written in HTML and it's marked with the <required> tag for validation. Like this <select name="users" width="200" size="11" style="outline:none" required>
And a submit button for the form <input type="submit" onclick="return confirm(\Are you sure to disable this user?\'); value="Disable user" formaction="disableuser">
But when I submit the form without selecting a user from the list it still fires the confirm pop-up, even nothing is selected. I'm stuck with this, can somebody help me? Thanks.
Try this..
function Submit() {
if(//check whether a user is selected)
{
var r = confirm("Are you sure to disable this user?");
if (r == true) {
//do what ever you need
}
else {
return;
}
}
else
{
alert('Please select a user!!!');
}
}
Invoke Submit() on onclick of submit button...
I am assuming that the code actually has size="1" instead of size="11", because with the latter, the problem does not arise (on modern browsers). For size=1, the first option is interpreted as selected, so the element satisfies the requiredness constraint even when the user has not made any selection. To avoid this, insert a dummy option with an empty value. It is customary to use it in a placeholder-like manner:
<select name="users" width="200" size="1" style="outline:none" required>
<option value="">Select a user:
<option>foo
<option>bar
</select>
The issue is explained in detail at Can I apply the required attribute to <select> fields in HTML5?
As always, you should not rely on any client-side checks; they are for user comfort, not for security. The processing of the form data server-side should be based on the assumption that the user is a malevolent hacker who uses a modified version of your form. In particular, in this case, the value of users can be literally anything.

How to populate input text field data based on button pressed

In my project i have 10 products for every product i have button called info, if i click on a info button a form popups in that i wanted to fill the first field(product name) automatically ....lets say for product soap i have info button
`info`
In the form
`<form>
<input type="text" id="product_name">
<input type="text" id="number">
</form>`
I want the field Product_name to be filled automatically based on button pressed
so how to get this ..plz help
i tried using
info
and my js
function reply_click(clicked_id)
{
//alert(clicked_id);
if(clicked_id == "1")
{
document.getElementById(product_name).value='Soap';
}
else
{
alert("button not pressed");
}
}
i tried this logic for example, i am able to read button click but iam unable to write to form...
some one please help me out
Thank you in advance
You are using id without quotes product_name but 'product_name'
should be
document.getElementById('product_name').value='Soap';
instead of
document.getElementById(product_name).value='Soap';
As stated by Suman, you need to provide 'product_name' as a string to getElementById(). Here is a working example of your approach: http://jsfiddle.net/CTnFt/
But since you will likely have many of these tags for many products, a simpler solution might be to place the value in a data- attribute of your tag and read it in your javascript function, instead of a larger, harder to maintain collection of if/elses. Here is a working example: http://jsfiddle.net/Rc9MG/
info
<form>
<input type="text" id="product_name" />
</form>
<script type="text/javascript">
function reply_click(element)
{
document.getElementById('product_name').value = element.getAttribute('data-product-name');
}
</script>

Categories