I'm looking to do a dropdown menu with user input, but I want the user to be able to add multiple options.
I was trying to do a datalist with this, but when it came time for multiple inputs then I read that datalist can only do that with email and files.
Here's an example of my current code:
HTML:
<input type="text" name="users" id="users" list="allowedUsers">
<datalist id="editUsers">
<option value="bob"></option>
</datalist>
JS:
$('#users').keypress(function(event){
var keyCode = (event.keyCode ? event.keyCode : event.which)
if(keyCode == '13') {
var inputVal = $(this).val();
$(#editUsers).append('<option value="'+inputVal+'">'+inputVal+'</option>')
}
});
The user can then click on a value and if they click on another either add that one in or when they do a comma then they can click to add. Not sure what would be easiest.
Thanks!
Chek this: https://selectize.github.io/selectize.js/
And in mid time maybe you could get away with something like this:
1 example:
It works by clicking the items, input is readonly...
$('#users').focus(function(){
$('#editUsers').show();
});
$('#editUsers').change(function() {
var val = $("#editUsers option:selected").text();
var inpoutVal = $('#users').val();
if (inpoutVal!=="") {
$('#users').val(inpoutVal+","+val)
}else{
$('#users').val(val)
}
});
#editUsers {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="users" id="users" readonly>
<select id="editUsers" multiple>
<option>Bob</option>
<option>Jhon</option>
<option>Yoda</option>
</select>
2nd example:
this is just something i trued to cook up, but it got out of hand, anyway try to pres some starting letter like B, or Y, then add cooma , . Anyway it does not definlty work as it should but maybe will someone get inspired by this failed attempt. ;)
Its late here cant work on it anymore...
$('#users').focus(function() {
$('#editUsers').show();
});
$("#users").bind('input', function() {
console.clear();
var inputVal = $("#users").val();
var inputVal2 = inputVal.split(",");
var last = inputVal2[inputVal2.length - 1];
$('#editUsers option').each(function() {
var selVal = $(this).val();
if (selVal.indexOf(last) > -1 && inputVal.indexOf(",") <= 0) {
$("#users").val(selVal + ",")
} else if (selVal.indexOf(last) > -1 && inputVal.indexOf(",") > -1) {
var newval = $("#users").val();
var newval2 = newval.split(",");
newval2.pop()
newval2
$("#users").val(newval2 + "," + selVal)
}
});
});
#editUsers {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="users" id="users">
<select id="editUsers" multiple>
<option>Bob</option>
<option>Jhon</option>
<option>Yoda</option>
</select>
Related
I have a DOM in which I want to prevent users from entering duplicate entries in html text input.
The above DOM is not in user's control. It is coming through php.
At this moment, I am focussing only on name="code[]".
This is what I have tried:
$(function(){
$('input[name^="code"]').change(function() {
var $current = $(this);
$('input[name^="code"]').each(function() {
if ($(this).val() == $current.val())
{
alert('Duplicate code Found!');
}
});
});
});
Problem Statement:
I am wondering what changes I should make in javascript code above so that when a duplicate code is entered, alert message "Duplicate code Found" should come up.
you need to add an eventlistener to each item, not an eventlistener for all. Then count inputs with same value, if there's more than 1, it's a duplicate.
Also ignore not-filled inputs.
Check following snippet:
$('input[name*="code"]').each(function() {
$(this).change(function(){
let value = $(this).val();
let count = 0;
$('input[name*="code"]').each(function() {
if ($(this).val() != '' && $(this).val() == value) {
count++;
if (count > 1) alert('duplicate');
}
});
});
$(this).addClass('e');
});
$('#createInput').on('click', function(){
let newInput = document.createElement("input");
newInput.name = 'code[]';
newInput.type = 'text';
newInput.className = 'whatever';
$('#inputGroup').append(newInput);
// repeat the eventlistener again:
$('input[name*="code"]:not(.e').each(function() {
$(this).change(function(){
let value = $(this).val();
let count = 0;
$('input[name*="code"]').each(function() {
if ($(this).val() != '' && $(this).val() == value) {
count++;
if (count > 1) alert('duplicate');
}
});
});
$(this).addClass('e');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="inputGroup">
<input name="code-1" type="text" class="whatever">
<input name="code-2" type="text" class="whatever2">
<input name="code-3" type="text" class="whatever3">
</div>
<input type="button" id="createInput" value="Add input">
Edit:
now works with dynamically created elements. The class 'e' works as flag to not insert 2 event listeners to the same node element, otherwise they will run in cascade, provoking unwanted behaviour.
You can use something like this, that converts the jQuery object to an Array to map the values and find duplicates. I added an option to add a style to the duplicated inputs, so the user knows which ones are duplicated.
function checkDuplicates(){
var codes = $('input[name^="code"]').toArray().map(function(element){
return element.value;
})
var duplicates = codes.some(function(element, index, self){
return element && codes.indexOf(element) !== index;
});
return duplicates;
}
function flagDuplicates(){
var inputs = $('input[name^="code"]').toArray();
var codes = inputs.map(function(element){
return element.value;
});
var duplicates = 0;
codes.forEach(function(element, index){
var duplicate = element && codes.indexOf(element) !== index;
if(duplicate){
inputs[index].style.backgroundColor = "red";
inputs[codes.indexOf(element)].style.backgroundColor = "red";
duplicates++
}
});
return duplicates;
}
$('input[name^="code"]').on("change", function(){
//var duplicates = checkDuplicates(); // use this if you only need to show if there are duplicates, but not highlight which ones
var duplicates = flagDuplicates(); // use this to flag duplicates
if(duplicates){
alert(duplicates+" duplicate code(s)");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="code-1" type="text">
<input name="code-2" type="text">
<input name="code-3" type="text">
I have a datalist connected to an input
<input list='typesOfFruit' placeholder="Enter a fruit...">
<datalist id='typesOfFruit'>
<option>Apple</option>
<option>Orange</option>
<option>Banana</option>
</datalist>
As the user is typing Ap... How can I make it be already selecting the top suggestion "Apple" so if it is correct they can just hit Enter, rather than have to press the down arrow and then enter.
EDIT: Similar question but no one answered correctly: How to auto select the first item in datalist (html 5)?
I need to auto select the top suggestion WHILE typing, not select the first item in the list statically. So if I press B, Banana will be the top suggestion, and I'd like to know if its possible to have it autofocus on it so the user can hit ENTER instead of down arrow enter
You can do this by maintaining a custom query filter for datalist options.
Try the below code. You can reduce boiler plate if you already know the options data in place.
Hope this helps!
var input = document.querySelector("input");
var options = Array.from(document.querySelector("datalist").options).map(function(el){
return el.innerHTML;
}); //Optional if you have data
input.addEventListener('keypress', function(e){
if(e.keyCode == 13){
var relevantOptions = options.filter(function(option){
return option.toLowerCase().includes(input.value.toLowerCase());
}); // filtering the data list based on input query
if(relevantOptions.length > 0){
input.value = relevantOptions.shift(); //Taking the first
}
}
});
<input list='typesOfFruit' placeholder="Enter a fruit...">
<datalist id='typesOfFruit'>
<option>Apple</option>
<option>Orange</option>
<option>Banana</option>
</datalist>
$("form").on('keydown', 'input[list]', function(e){
if(e.keyCode == 9 || e.keyCode == 13){
const oInput = this;
const aOptions = $('#' +$(oInput).attr('list')+ ' option').map(function() {return this.text}).toArray();
var aRelOptions = aOptions.filter(function(sOption){
return new RegExp(oInput.value.replace(/\s+/, ".+"), "gi").test(sOption);
});
if(aRelOptions.length > 0){
this.value = aRelOptions.shift();
}
if(e.keyCode == 13) return false;
}
}).on("change", 'input[list]', function() {
$(this).attr("placeholder", this.value);
this.blur();
}).on('focus', 'input[list]', function() {
$(this).attr("placeholder", this.value);
this.value = "";
}).on('blur', 'input[list]', function() {
this.value = $(this).attr("placeholder");
});
I'm new at Javascript and I'm trying to reveal additional info only if any 2 out of 3 checkboxes are checked.
Here is my code so far (I'm trying to enter my code in the question but It's not working, sorry. I also may have made it more complicated then necessary, sorry again). I did place my code in the Demo.
<script>
var checkboxes;
window.addEvent('domready', function() {
var i, checkbox, textarea, div, textbox;
checkboxes = {};
// link the checkboxes and textarea ids here
checkboxes['checkbox_1'] = 'textarea_1';
checkboxes['checkbox_2'] = 'textarea_2';
checkboxes['checkbox_3'] = 'textarea_3';
for ( i in checkboxes ) {
checkbox = $(i);
textbox = $(checkboxes[i]);
div = $(textbox.id + '_container_div');
div.dissolve();
showHide(i);
addEventToCheckbox(checkbox);
}
function addEventToCheckbox(checkbox) {
checkbox.addEvent('click', function(event) {
showHide(event.target.id);
});
}
});
function showHide(id) {
var checkbox, textarea, div;
if(typeof id == 'undefined') {
return;
}
checkbox = $(id);
textarea = checkboxes[id];
div = $(textarea + '_container_div');
textarea = $(textarea);
if(checkbox.checked) {
div.setStyle('display', 'block');
//div.reveal();
div.setStyle('display', 'block');
textarea.disabled = false;
} else {
div.setStyle('display', 'none');
//div.dissolve();
textarea.value = '';
textarea.disabled = true;
}
}
<label for="choice-positive">
<script type="text/javascript">
function validate(f){
f = f.elements;
for (var c = 0, i = f.length - 1; i > -1; --i)
if (f[i].name && /^colors\[\d+\]$/.test(f[i].name) && f[i].checked) ++c;
return c <= 1;
};
</script>
<label>
<h4><div style="text-align: left"><font color="black">
<input type="checkbox" name="colors[2]" value="address" id="address">Full Address
<br>
<label>
<input type="checkbox" name="colors[3]" value="phone" id="phone">Phone Number <br>
<label>
<input type="checkbox" name="colors[4]" value="account" id="account">Account Number <br>
</form>
<div class="reveal-if-active">
<h2><p style = "text-decoration:underline;"><font color="green">Receive the 2 following
pieces of info:</h2></p>
</style>
Sorry i wasn't able to exactly use the code you provided but tried to change just enough to get it working.
I've uploaded a possible solution to JSFiddle - you essentially can add event listeners to the checkboxes that recheck when clicked how many are selected and show/hide via removing/adding a class e.g. additionalContactBox.classList.remove('reveal-if-active');
I have the follow script on a form.
jQuery(document).ready(function($) {
$('#bizloctype').on('change',function() {
$('#packages div').show().not(".package-" + this.value).hide();
});
});
</script>
Basically, depending on the value of the select box #bizloctype (value="1","2","3" or "4") the corresponding div shows and the rest are hidden (div class="package-1","package-2","package-3", or "package-4"). Works perfectly.
BUT, I need to add an additional condition. I need the text box #annualsales to be another condition determining which div shows (if the value is less than 35000 then it should show package-1 only, and no other packages.
I think the below script works fine when independent of the other script but I need to find out how to marry them.
<script>
$("#annualsales").change(function(){
$(".package-1,.package-2,.package-3,.package-4").hide();
var myValue = $(this).val();
if(myValue <= 35000){
$(".package-1").show();
}
else
{
$(".package-2").show();
}
});
</script>
Help please?
I would remove the logic from the anonymous functions and do something like this:
// handle display
function displayPackage( fieldID ) {
var packageType = getPackageType(fieldID);
$('#packages div').show().not(".package-" + packageType).hide();
}
// getting the correct value (1,2,3 or 4)
function getPackageType( fieldID ) {
// default displayed type
var v = 1;
switch(fieldID) {
case 'bizloctype':
// first check it annualsales is 1
v = (getPackageType('annualsales') == 1) ?
1 : $('#' + fieldID).val();
break;
case 'annualsales':
v = (parseInt($('#' + fieldID).val(),10) <= 35000) ? 1 : 2;
break;
}
return v;
}
jQuery(document).ready(function($) {
$('#bizloctype,#annualsales').on('change',function() {
displayPackage($(this).attr('id'));
});
});
If I understand your question properly, try this code out. It first adds an onChange listener to #annualsales which is the code you originally had. Then, for the onChange listener for #bizloctype, it simply checks the value of #annualsales before displaying the other packages.
jQuery(document).ready(function($) {
// Check value of #annualsales on change
$("#annualsales").change(function(){
$(".package-1,.package-2,.package-3,.package-4").hide();
var myValue = $(this).val();
if(myValue <= 35000){
$(".package-1").show();
}
// Only show other packages if value is > 35000
$('#bizloctype').on('change',function() {
$(".package-1,.package-2,.package-3,.package-4").hide();
if ($('#annualsales').val() <= 35000) {
$(".package-1").show();
} else {
$('#packages div').show().not(".package-" + this.value).hide();
}
});
});
Since you already use JQuery you can use the data() function to create a simple but dynamic condition system. For example, you could annotate each element with the required conditions and then attach change listeners to other elements to make the condition active or inactive for the elements.
For example, with this HTML:
<div id="conditions">
Condition 1: <input type="checkbox" id="check1" /> <= check this<br/>
Condition 2: <input type="checkbox" id="check2" /><br/>
Condition 3: <input type="text" id="value1" /> <= introduce 1001 or greater<br/>
Condition 4: <input type="text" id="value2" /><br/>
</div>
<p id="thing" data-show-conditions="check1 value1-gt-1000"
style="display: none;">
The thing to show.
</p>
And this Javascript:
function setShowCondition(el, condition, active) {
var conditions = $(el).data('conditions') || {};
conditions[condition] = active;
$(el).data('conditions', conditions);
var required = ($(el).data('show-conditions') || "").split(" ");
var visible = required.every(function (c) {
return conditions[c];
});
if (visible) {
$(el).show();
} else {
$(el).hide();
}
}
$("#conditions input[type='checkbox'").change(function () {
setShowCondition('#thing',
$(this).attr('id'),
$(this).is(':checked'));
});
$("#value1").change(function () {
var number = parseInt($(this).val());
setShowCondition('#thing', 'value1-gt-1000', number > 1000);
});
You can maintain conditions easily without having to nest and combine several if statements.
I've prepared a sample to show this in https://jsfiddle.net/2L5brd80/.
I'm very new to javascript. I read this link and tried to customize it but it is not working: Disable an input field if second input field is filled
I want to allow people to toggle between two options-city and zipcode. I want to enable whatever field they chose last and disable the other. For example, if they are on the zipcode tab and press the submit button, whatever input it is in the zipcode gets submitted and not the city & vice versa.
The html is:
<ul class="tabs">
<li><a class="border-radius top med" href="#city">City</a></li>
<li><a class="border-radius top med" href="#zipcode">Zipcode</a></li>
</ul>
<div id="city"><label class="IDX-advancedText">City</label>
<select id="aht-home-city" name="city[]" class="IDX-select " autocomplete="off">
<option value="2115">Austin</option>
<option value="2718">Bartlett</option>
</div>
<div id="zipcode"><label class="IDX-advancedText">Zipcode</label>
<input class="IDX-advancedBox IDX-advWildText" id="IDX-aw_zipcode" type="text"
maxlength="255" name="aw_zipcode" value="" /></div>
The script is:
var dis1 = document.getElementById("city");
dis1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("zipcode").disabled = true;
}
}
var dis2 = document.getElementById("zipcode");
dis1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("city").disabled = true;
}
}
Any help is very much appreciated! The website is http://austinhometeam.staging.wpengine.com/joyce-newsletter/
Like I told you in the comment, you need to change the ID in the "getElementById".
I also add the re-enabled the field when the other one is empty.
I add an empty value in the select, when the null is selected, the zip code's field return enable.
HTML
<ul class="tabs">
<li><a class="border-radius top med" href="#city">City</a></li>
<li><a class="border-radius top med" href="#zipcode">Zipcode</a></li>
</ul>
<div id="city"><label class="IDX-advancedText">City</label>
<select id="aht-home-city" name="city[]" class="IDX-select " autocomplete="off">
<option value=""></option>
<option value="2115">Austin</option>
<option value="2718">Bartlett</option>
</select>
</div>
<div id="zipcode"><label class="IDX-advancedText">Zipcode</label>
<input class="IDX-advancedBox IDX-advWildText" id="IDX-aw_zipcode" type="text"
maxlength="255" name="aw_zipcode" value="" /></div>
Javascript :
var dis1 = document.getElementById("aht-home-city");
var dis2 = document.getElementById("IDX-aw_zipcode");
dis1.onchange = function () {
if (dis1.value !== "" || dis1.value.length > 0) {
dis2.disabled = true;
} else {
dis2.disabled = false;
}
};
dis2.onchange = function () {
if (dis2.value !== "" || dis2.value.length > 0) {
dis1.disabled = true;
} else {
dis1.disabled = false;
}
};
There is a working example :
JSBin Example
Looking for something like this behaviour?
var last = "";
var dis1 = document.getElementById("aht-home-city");
dis1.onchange = function () {
last = "city";
document.getElementById("IDX-aw_zipcode").disabled = true;
}
var dis2 = document.getElementById("IDX-aw_zipcode");
dis2.onchange = function () {
last = "zipcode";
if (this.value != "" || this.value.length > 0) {
document.getElementById("aht-home-city").disabled = true;
}
}
Check this jsFiddle
Note: there was also a missing </select> tag in the HTML.