Is there a way by which I can validate select two only to allow a minimum number of selection length as it has for maximumSelectionLength.
I have tried minimumSelectionLength but it does not work for me :
<link rel="stylesheet" type="text/css" href="select2/select2.min.css" />
<script src="select2/select2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".selecte").select2();
maximumSelectionLength: 15;
});
</script>
So I want the button not to submit until the user selects up to like 3 items.
Any ideas or suggestion.
select2 plugin don't have any attribute for this purpose so you could validate the select element want in submit event make you condition then submit when it's achieved :
$('form').on('submit', function(){
var minimum = 3;
if($(".selecte").select2('data').length>=minimum)
return true;
else
return false;
});
Hope this helps.
$(".selecte").select2();
$('form').on('submit', function(){
var minimum = 2;
if($(".selecte").select2('data').length>=minimum){
alert('Submited...')
return true;
}else {
alert('Please shoose at least '+minimum+' item(s)')
return false;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.css" rel="stylesheet"/>
<script src="http://cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.min.js"></script>
<form>
<select multiple class="selecte" style="width:300px">
<option value="AL">Alabama</option>
<option value="Am">Amalapuram</option>
<option value="An">Anakapalli</option>
<option value="Ak">Akkayapalem</option>
<option value="WY">Wyoming</option>
</select>
<br>
<input type='submit' />
</form>
var min = 1;
$('input[type="submit"]').on('click', function(event){
if ($('#group_select option:selected').size() < min) {
alert("Need at least one group");
event.preventDefault();
}
});
Popup a alert if the min requirement is not satisfied.
Use .val() in your JS to get the value of the input, after that you can use regex in an if statement that if it returns true ( meets the value requirement set by regex ) then it will submit. You can use console.log() the value, to see what data you are working with. (regex101.com is a great place to build your regex code.)
Related
I have datalist like below -
<input id="name" list="allNames" />
<datalist id="allNames">
<option value="Adnan1"/>
<option value="Faizan2"/>
</datalist>
What I want is, when an item is typed in completely(for example say in input box when user completely type "Adnan1") or selected from list, then I want an event. I tried couple of approaches but both doesn't help me so far. Approaches are -
$("#name").change(function(){
console.log("change");
}
problem with this is, the event only gets triggered when input gets out of focus I.e. when I click somewhere in the screen.
I also tried
$("#name").bind('change', function () {
console.log('changed');
});
but the callback gets triggered each time when I type in. I actually need to make an AJAX call when item is completely selected. Either via type-in or by selecting from dropdown.
First approach is bad for user perspective because he has to make extra click and second has disadvantage as for every letter an event will be triggered.
All I want is an event when either user made a selection or typed complete sentence. is there a way to achieve this? any event that I missing and that can solve my problem.
On modern browsers, you can use input event, e.g:
$("#name").on('input', function () {
var val = this.value;
if($('#allNames option').filter(function(){
return this.value.toUpperCase() === val.toUpperCase();
}).length) {
//send ajax request
alert(this.value);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="name" list="allNames" />
<datalist id="allNames">
<option value="Adnan1" />
<option value="Faizan2" />
</datalist>
PS: as input event has better support than datalist element, there is indeed no reason to not use it if you are already using datalist element.
You can use input event for achieving such functionality, as below :
$(document).ready(function() {
$('#name').on('input', function() {
var userText = $(this).val();
$("#allNames").find("option").each(function() {
if ($(this).val() == userText) {
alert("Make Ajax call here.");
}
})
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="name" list="allNames" />
<datalist id="allNames">
<option value="Adnan1" />
<option value="Faizan2" />
</datalist>
Simple solution
document.getElementById('name').addEventListener('input', function () {
console.log('changed');
});
Hacky as a sin, but works for me. (Note that if you are typing 'Rum-Cola' it doesn't stop on the 'Rum' option)
const opts = $("option").map(function(){return this.value;}).get();
$("#favourite-drink").on("keydown", function(e){
if(e.key){ // in case of mouse event e.key is 'undefined'
if (e.key === "Enter") { // looks like user wants to confirm the choice
if(opts.indexOf(this.value) >= 0){
this.blur();
console.log("Selected: " + this.value);
}
}
else {
this.setAttribute("data-keyboardinput", "true"); // remember that it's keyboard event
setTimeout(function(){ //and keep it in memory for 100ms
this.removeAttribute("data-keyboardinput")
}.bind(this), 100);
}
}
});
$("#favourite-drink").on("input", function(){
if(!this.dataset.keyboardinput && opts.indexOf(this.value) >= 0){ // if it's not a key press followed event
console.log("Selected: " + this.value);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Choose a drink:</p>
<input id="favourite-drink" list="drinks">
<datalist id="drinks">
<option value="Rum"></option>
<option value="Rum-Cola"></option>
<option value="Vodka"></option>
</datalist>
Check if this works for you :
var dataList=[];
$("#allNames").find("option").each(function(){dataList.push($(this).val())})
console.log(dataList);
$("#name").on("keyup focus blur change",function(){
if(dataList.indexOf($(this).val())!=-1)
console.log("change");
})
I pushed datalist options into array , and on change event keyup , blur or focus , i check if input value exists in my datalist array.
In addition to what was said above, we can also check the inputType of the input which must correspond to "insertReplacementText"
function textThatComesFromADatalist (event){
const inputType = event.inputType;
const isReplacingText = (typeof inputType === "undefined")
|| (inputType === "insertReplacementText");
return isReplacingText;
}
function onInput(event) {
if(textThatComesFromADatalist(event)){
alert('selected: '+event.target.value);
}
}
<input oninput="onInput(event)" list="ice-cream-flavors" id="ice-cream-choice" name="ice-cream-choice" />
<datalist id="ice-cream-flavors">
<option value="Chocolate">
<option value="Coconut">
<option value="Mint">
<option value="Strawberry">
<option value="Vanilla">
</datalist>
Simple solution is that check the input text value exist in datalist or not, and if it does, run an ajax request.
$("#input_form").on('input', function(event){
if ($("#input_datalist option[value='" + $('#input_form').val() + "']").val() != undefined) {
//send ajax request
}
});
There are two selection buttons which need client-side validation. The user must select one of them, and if user chooses one, the other one will be disabled automatically.
This my script:
<html>
<head>
<script type="text/javascript">
function Check() //this the funciton for diasbled
{
var x =document.getElementById("supexp1");
var y =document.getElementById("supexp2");
if(x.value != "")
{
document.form1.supexp2.disabled=true;
}
else if(y.value != "")
{
{
document.form1.supexp1.disabled=true;
}
}
}
</script>
</head>
<body>
<form method="POST" action="destination.php" id="form1">
<select name="SUPEXP" id="supexp1" data-native-menu="false" onChange="Check()">
<option >Ekspedisi Local1</option> //this selection 1
<option >Ekspedisi Local2</option> //this selection 1
<option >Ekspedisi Local3</option> //this selection 1
</select>
<select name="SUPEXP" id="supexp2" data-native-menu="false" onChange="Check2()">
<option >Ekspedisi Expor2</option> //this selection 2
<option >Ekspedisi Expor2</option> //this selection 2
<option >Ekspedisi Expor2</option> //this selection 2
</select>
</form>
</body>
</html>
I use the jquerymobile framework and selection connect to the database. That code (JavaScript) is not running.
I hope this is what you trying to do based on your description here is a jsfiddle
$(document).ready(function() {
$('#supexp1').change(function() {
$('#supexp2').attr("disabled" , "disabled")
});
$('#supexp2').change(function() {
$('#supexp1').attr("disabled" , "disabled")
});
});
Try this code
if(x.value != ""){
document.getElementById("supexp2").disabled=true;
} else if(y.value != "") {
document.getElementById("supexp1").disabled=true;
}
I guess to get the value of the selected item you need to use some thing like this
var e = document.getElementById("supexp1");
var x = e.options[e.selectedIndex].value;
instead of
var x =document.getElementById("supexp1");
do the same for Y
I've a textBox control and would like my users to only be able to enter ....#firm1.com' or '....#firm2.com'
How can I do this with a JavaScript function? The function must take a textbox value.
It doesn't make sense to give the user a textbox but allowing him to write two values only,
You should use a dropdown instead:
<select>
<option value="0"> #firm1.com </option>
<option value="1"> #firm2.com </option>
</select>
Update:
If you really have to use textbox for some unknown reason:
$('#textboxId').change(function(){
if (!this.value.match(/(#firm1.com|#firm2.com)$/g))
alert('invalid value');
});
Live DEMO
Try this code-
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
var patt1 = "[A-Za-z0-9._%+-]+#firm(1|2).com";
function demoShowMatchClick(str) {
var re = new RegExp(patt1);
var m = re.exec(str);
if (m == null) {
document.getElementById("match").innerHTML = "no match";
} else {
document.getElementById("match").innerHTML = "match";
}
}
</script>
</head>
<body>
<span id="match"></span>
<input type="text" onkeyup="demoShowMatchClick(this.value)" />
</body>
</html>
This was interesting. In a select dropdown, trying not to use jQuery (with the exception of easing some of my pain on recreation), I ran into an issue that doesn't properly let any current browsers catch the proper selected option. Here is my code, for the page that recreates the issue (remember, no jQuery to necessarily solve issue, but more or less just telling me what I am doing wrong.
This one has me stumped.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<div id="select-holder" />
<input id="some-button" type="button">
<script type="text/javascript">
$("#some-button").click(function(){
var select_element = document.createElement('select');
select_element.setAttribute("id", "some-id");
select_element.setAttribute("name", "some-name");
var options = new Array();
for ( var i = 0; i < 3; i++ ){
options.push(new Option("Option " + i, "Value" + i, false, false));
}
options[1].setAttribute("selected", "selected");
for ( var option in options ){
select_element.appendChild(options[option]);
}
$("#select-holder").append(select_element);
});
</script>
</body>
</html>
The html this creates is:
<select id="some-id" name="some-name">
<option value="Value0">Option 0</option>
<option value="Value1" selected="selected">Option 1</option>
<option value="Value2">Option 2</option>
</select>
But the anomaly here is that (in firefox at least), the selected option ends up being Option 0, which isn't the selected DOM element. In IE6, this select dropdown doesn't work at all.
There is an alternate method that does work, which includes piecing the options together manually, which works in all browsers that I have tested.
A small change made it work for me in Firefox:
...
//options[1].setAttribute("selected", "selected");
options[1].selected = true;
...
I'm manipulating the DOM element's attributes directly. Not sure why your method doesn't work. Maybe you should keep both lines so that the HTML generated has the selected = "selected" in it.
some old thread - however try something like this:
var idx=0;
while(obj.options[idx]) {
if(obj.options[idx].value==value) obj.options[idx].setAttribute('selected',true);
else obj.options[idx].removeAttribute('selected');
idx++;
}
Use selectedIndex to set the selected index of a select object.
options.selectedIndex = 1;
Here is the working code, which seems like more of a Hack!
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<div id="select-holder" />
<input id="some-button" type="button">
<script type="text/javascript">
$("#some-button").click(function(){
var select_element = document.createElement('select');
select_element.setAttribute("id", "some-id");
select_element.setAttribute("name", "some-name");
for ( var i = 0; i < 3; i++ ){
var option_element = document.createElement('option');
option_element.setAttribute('value', "Value" + i);
option_element.appendChild( document.createTextNode( "Option " + i ) );
if (i == 1){
option_element.setAttribute("selected", "selected");
}
select_element.appendChild(option_element);
}
$("#select-holder").append(select_element);
});
</script>
</body>
</html>
options[1].setAttribute("selected", "selected");
is likely where your issue lies. The output you're getting is:
<option value="Value1" selected="selected">Option 1</option>
and the standard is:
<option value="Value1" selected>Option 1</option>
You may be able to do:
options[1].selected = true;
I want to have a drop down menu where a user can select from several predefined options but i also want to give him the option of inserting a user specific value, i was thinking having one of the options as "user specific" which will in turn allow the user to insert a user specif entry in a text box that appears or is editable when user selects the "user specific" option. any one have any ideas how i can implement this is HTML and Javascript?
thank you
Attach an onchange event to the select and when he selects "Custom" or something like that, make some input visible below the select. This input should be initially hidden (css display:none). When the user selects "custom" make it display:inline.
Jukka wrote an article on how to create a combobox-like effect. I've only skimmed it, but it looks accessible and his content is usually of very high quality.
You can go about like:
<select id="myid" onchange="doIt(this);">
optons...
</select>
<script type="text/javascript">
function doIt(field) {
if (field.value === 'user specific')
{
var tbox = document.createElement('input');
tbox.setAttribute('type', 'text');
document.form_name.appendChild(tbox);
}
}
</script>
See here: http://jsfiddle.net/EscRV/
html
<select id="mySelect">
<option>value 1</option>
<option value="[new]">new</option>
</select>
js
// get a cross-browser function for adding events, place this in [global] or somewhere you can access it
var on = (function(){
if (window.addEventListener) {
return function(target, type, listener){
target.addEventListener(type, listener, false);
};
}
else {
return function(object, sEvent, fpNotify){
object.attachEvent("on" + sEvent, fpNotify);
};
}
}());
var mySelect = document.getElementById("mySelect");
on(mySelect, "change", function(){
if (this.value === "[new]") {
var newOptionName = prompt("input new option");
if (newOptionName){
mySelect.options[mySelect.options.length] = new Option(newOptionName);
this.value= newOptionName;
}
}
});
Following code will help to solve your problem.
<html>
<head></head>
<body>
<select id="sbox">
<option value="1" onclick="hideUserOption();">First option</option>
<option value="2" onclick="hideUserOption();">second option</option>
<option value="3" onclick="showUserOption();">User Specific</option>
</select>
<div id="userOptions" style="display:none">
<input type="text" />
<input type="submit" value="Save"/>
</div>
<script type="text/javascript">
function showUserOption() {
var userOptions = document.getElementById("userOptions");
userOptions.style.display = "block";
}
function hideUserOption() {
var userOptions = document.getElementById("userOptions");
userOptions.style.display = "none";
}
</script>
</body>
</html>