jQuery, same function for multiple ids - javascript

i want to clear specified input if the value is not number. function works for one ID, but i want it to work for multiple. of course i can write function multiple times but i dont want to do that.
the following code gets effect only for input with id "d". i dont know how to identify other ids. can anyone help?
<input id="d" />
<input id="d2" />
<input id="d3" />
<script type="text/javascript">
$('#d,d2,d3').keyup(function(){
if($('#d,d2,d3').val() != "") {
var value = $('#d,d2,d3').val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var intRegex = /^\d+$/;
if(intRegex.test(value)) {}
else {
$(this).val('');
}
}
});
</script>

Instead of $('#d,d2,d3') use $('#d, #d2, #d3') and for the if statement use $(this).val()

You can use starts with selector instead of putting in multiple ids like this:
$('[id^=d]')
Above selector will work for all elements whose ids start with d eg d1, d2, d3 and so on.
Here is how your code should be (fixing other errors as well):
$('[id^=d]').keyup(function(){
if(this.value != "") {
var value = this.value.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var intRegex = /^\d+$/;
if(intRegex.test(value)) {}
else {
this.value = '';
}
}
});

$('input[id^=d]').keyup(function() {
var val = $.trim( this.value ); // or $.trim( $(this).val() )
if (val != "") {
var value = val.replace(/^\s\s*/, '').replace(/\s\s*$/, ''),
intRegex = /^\d+$/;
if (intRegex.test(value)) {
// do something
} else {
$(this).val('');
}
}
});​
[id^=d] is a start with selector that means, id start with d.
Read about jQuery start selector

You forgot the # for d2 & d3. And also a this.
$('#d,#d2,#d3').keyup(function(){
if($(this).val() != "") {
var value = $(this).val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var intRegex = /^\d+$/;
if(intRegex.test(value)) {}
else {
$(this).val('');
}
}
});

You forgot the hash for the other two Ids:
$('#d,#d2,#d3')
see also
jQuery Multiple ID selectors

You can add class attribute
<input id="d" class="A"/>
<input id="d2" class="A"/>
<input id="d3" class="A"/>
use following selector by class name
$('.A').keyup

Related

prevent users from entering duplicate entries in text inputs in javascript

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">

Check for partial match in JavaScript if statement

I've got elements set up something like this:
<div class="cat" data-cat="example-cat, test-cat, test-category">
...
</div>
<div class="cat" data-cat="test-category">
...
</div>
<div class="cat">
...
<div class="cat" data-cat="example-cat, test-category">
...
</div>
<div class="cat" data-cat="test-category, one-more-cat">
...
</div>
</div>
Using JavaScript, I need to check each bit of text between commas for a match with a user selected value. For example, if the user selected "test-cat," I need to check each div to see if data-cat matches the selection. If it does, I need to add class="active" to each matching div.
Part of the trick is that if the user selects test-cat, a div with a data-cat of test-category should not return positive. Only exact matches should be consider matches.
I had already set up a complex filtering system with support for multiple filters, but the client wants to be able to set multiple categories per div, which is making this tricky. I have a script set up to show matches if the attribute is an exact match, and I'll be trying to modify this to work as I need it to:
$(document).ready(function() {
var changedOnce = false;
$("#filters select").change(function() {
$(".cat").each(function() {
$(this).attr("data-match", "true");
$(this).removeClass("open");
});
$("#filters select").each(function() {
var filter = $(this).attr("name");
var value = $(this).val();
$(".cat").each(function() {
if ($(this).attr("data-match") === "false") {
return true;
}
var attr = $(this).attr("data-" + filter);
var childAttr = $(this).find(".cat").attr("data-" + filter)
if ((typeof attr !== typeof undefined && attr !== false) || (typeof childAttr !== typeof undefined && childAttr !== false)) {
if ($(this).attr("data-" + filter) === value || $(this).find(".cat").attr("data-" + filter) === value || value === "") {
$(this).attr("data-match", "true");
$(this).parents(".cat").attr("data-match", "true");
} else {
$(this).attr("data-match", "false");
return true;
}
} else {
if (value !== "") {
$(this).attr("data-match", "false");
return true;
} else {
$(this).attr("data-match", "true");
$(this).parents(".cat").attr("data-match", "true");
}
}
});
});
});
});
My filters are set up something like:
<div id="filters">
<select name="cat">
<option value="test-cat">Test Cat</option>
<option value="example-cat">Example Cat</option>
...
</select>
...
<select name="nth-filter">
...
</select>
</div>
It's probably not the most elegant solution (I'm no JavaScript master), but it was working, until I made this most recent change. If you need more information, just let me know.
UPDATE: Here's my current script, using .data() and .split() as suggested. I'm having trouble getting the parent category to show as a miss if all its children are misses, but I'll post a separate question for that.
$(document).ready(function() {
$("#filters select").change(function() {
$(".cat").each(function() {
$(this).data("match", true);
$(this).css("opacity", "1");
// $(this).removeClass("open");
});
$("#filters select").each(function() {
var filter = $(this).attr("name");
var value = $(this).val();
$(".cat").not(".primary").each(function() {
if ($(this).data(filter)) {
var match = $(this).data("match");
var attributes = $(this).data(filter).split(", ");
var i = 0;
$(attributes).each(function() {
if (value && attributes[i] !== value) {
match = false;
} else {
match = true;
return true;
}
i++;
});
$(this).data("match", match);
}
if ($(this).data("match") === false) {
$(this).css("opacity", "0.25");
} else {
$(this).css("opacity", "1");
}
});
});
});
});
You can use the String's split function to split the comma-separated values into an array, and then use the Array's indexOf function to check for a match.
var attr = $(this).attr("data-" + filter);
if (attr && (attr.split(/[\s*,\s*]+/).indexOf() >= 0)) {
Note: I left out this part of the check: attr !== false. attr should either be a String or undefined, so it will never be false. Did you mean to check if it is the string "false"?
Also, when you call the following:
var childAttr = $(this).find(".cat").attr("data-" + filter)
You should be aware that .attr() will return the value of the first matched element, and from your markup it looks like there could be multiple matched elements.

I want to disable the button if specific text has been found in any label

I want to disable the button if specific text has been found in any label.
The following code doesn't run because aTags[i].innerText is not equal to searchText all the time which is wrong because the label has inner text = "a" and the searchText variable have "a" as text - I need it to run in IE
<html>
<script language="javascript">
$(document).ready(function () {
var aTags = document.getElementsByTagName("label");
var searchText = "a";
var found;
for (var i = 0; i < aTags.length; i++) {
if (aTags[i].innerText == searchText) {
document.getElementById('choose').disabled=true;
break;
}
else
{
alert("failed")
}
}
});
</script>
<label> a </label> <br/>
<label> b </label> <br/>
<label> c </label> <br/>
<input type='button' value='choose' id='choose' />
</html>
Seems like there should be easier ways to do that with jQuery
$(function () {
var searchText = "a";
$('#choose').prop('disabled', function() {
return $('label').filter(function(_,el) {
return $.trim( $(el).text() ) === searchText;
}).length > 0;
});
});
FIDDLE
The issue is that your label contains " a " (with the spaces), but you're comparing with "a" (no spaces).
If you want to ignore the spaces, you can use jQuery's $.trim(...) to trim the text off the innerText.
But as you're using jQuery, you can dramatically reduce that code:
$(document).ready(function() {
var searchText = "a";
var found = false;
$("label").each(function() {
found = $.trim($(this).text()) === searchText;
if (found) {
return false; // No need to keep looking
}
});
$("#choose").prop("disabled", true);
});
Since you're already using jQuery, you can do what you like with much less complexity.
This will work:
(function ($) {
var searchText = "a";
$('label').each(function(){
if ($.trim($(this).text()) === searchText) {
$('#choose').prop('disabled', true);
}
});
})(jQuery);
You have to trim label's text. Try with:
if (aTags[i].innerText.trim() == searchText)
or without trim method:
if (aTags[i].innerText.replace(/^\s+|\s+$/g, '') == searchText)
If you want to match if a substring exists you can try with
aTags[i].innerText.indexOf(searchText) > -1
instead of
aTags[i].innerText == searchText

Displaying array from values in a dynamic div

Im would like to know how can I get the values from the div span and create a array() with which I could later on create a query to the database. Im trying to figure it somehow out but I just can't.
HTML
<form>
<span class="input-component"><input type="text"/><a href=#></a></span>
</form>
<br><br>
<div id="numcontainer">
<span class="containernum"></span><br>
</div>
Java script
jQuery(function($) {
var values = [];
$('#numcontainer').on('click', 'a.js-delete', function(e) {
$(this).prev().remove(); // the <span>
$(this).next().remove(); // the <br>
$(this).remove(); // the <a> itself
});
$('form input[type=text]').change(fileChangeHandler);
function fileChangeHandler() {
var form = $(this).closest('form');
}
var form = $(this).closest('form');
$('form .input-component input').on("propertychange keyup input paste",addInput);
onlyNums($('form .input-component input'));
function addInput() {
var remainingChars = $(this).val().length;
if (remainingChars == 24) {
if ($('.containernum').text() == '') {
$('.containernum').text($(this).val());
} else {
$('#numcontainer').append('<span class="containernum">'+$(this).val()+'</span><a class="js-delete href=#>[X]</a><br>');
}
$(this).val(''); // does empty the text input
$('.containernum').each(function(index){
// Your code
console.log( $(this).html() );
});
values.push($(this).val());
console.log(values);
}
}
function onlyNums($elem){
$elem.keydown(function(event) {
// Allow only backspace and delete
if ( event.keyCode == 46 || event.keyCode == 8 ) {
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
if (event.keyCode < 48 || event.keyCode > 57 ) {
event.preventDefault();
}
}
});
}
});
Example jsFiddle
Thanks for your time
You want to store values; why not use hidden inputs? Instead of creating spans with the same class, create input elements with the same name.
<div id="numcontainer">
<input type="hidden" name="myNums" value="305" />
<input type="hidden" name="myNums" value="49" />
</div>
Then, when you want to get the values you would just need to do something like this:
var values = [];
$("#numcontainer input:hidden[name='myNums']").each(function() {
values.push( $(this).val() );
});
If your values aren't related, you just name them something different.
$('span.containernum').html()
OR
$('span.containernum').text()
would do the trick. You will got the html string that you can implode or do whatever you want.
See https://stackoverflow.com/a/1910830/2806497 for the difference between the two functions.

How to hide the parent of an unchecked checkbox?

I have a set of random/dynamic generated div checkboxes:
<div>A1 <input type='checkbox' name='A[]' value='A1'> </div>
<div>A2 <input type='checkbox' name='A[]' value='A2'> </div>
<div>A3 <input type='checkbox' name='A[]' value='A3'> </div>
<div>B1 <input type='checkbox' name='B[]' value='B1'> </div>
<div>B2 <input type='checkbox' name='B[]' value='B2'> </div>
<div>C1 <input type='checkbox' name='C[]' value='C1'> </div>
What I am trying to do is when the user:
checks any A then the others will hide (entire div) but all A will still show.
unchecks a checkbox, then all A, B, C will show again.
This is because I am preventing the user from checking a mix of options.
PS:
You can provide a solution that might need me to modify the generated output of checkboxes.
try this fiddle
$("input[type=checkbox]").on("change", function() {
var thisName = $(this).attr("name");
if($(this).is(':checked')){
$(':checkbox').parent().hide();
$('input:checkbox[name|="'+thisName+'"]').parent().show();
} else {
$(':checkbox').parent().show();
}
});​
Try this one,
$('input:checkbox').click(function(){
if($(this).attr('checked') == 'checked'){
$('input:checkbox').parent('div').hide();
$('input:checkbox[name="'+$(this).attr('name')+'"]').parent('div').show();
}else{
if(!$('input:checkbox[checked="checked"]').length){
$('input:checkbox').parent('div').show();
}
}
})
​
Demo: http://jsfiddle.net/muthkum/uRd3e/3/
You can use some JQuery traversing to hide the non-matching elements:
// add the event handler
$("input[type=checkbox]").on("change", function() {
// get whether checked or unchecked
var checked = $(this).prop("checked") === true;
// get the name of the clicked element (eg, "A[]")
var thisName = $(this).prop("name");
// get the name of the clicked element (eg, "A[]")
var thisName = $(this).prop("name");
// get the grandparent element
$(this).parent().parent()
// get all the checkboxes
.find("input[type=checkbox]")
// filter to only the ones that don't match the current name
.filter(function(i, e) { return e.name != thisName; })
// hide or display them
.css("display", checked ? "none" : "");
});
you can simple do it like this
$('input[type=checkbox]').change(function () {
if ($(this).attr('checked')) {
var Name = $(this).prop("name");
$('div').filter(function(){
return $(this).find('input[type=checkbox]').prop("name") != Name;
}).hide();
}
else
{
$('input[type=checkbox]').attr('checked',false);
$('input[type=checkbox]').parent('div').show();
}
});​
Live Demo
Try code bellow:
$(":checkbox").click(function() {
var identifier = $(this).val().substring(0, 1);
$("input[type='checkbox']").each(function() {
if ($(this).val().indexOf(identifier) != -1) {
$(this).parent().show();
} else {
$(this).parent().hide();
}
});
if ($("input:checked").length == 0) {
$("input[type='checkbox']").parent().show();
}
});
You can try on jsFiddle
This will hide all other checkbox types when FIRST of a type is checked and show all the other checkbox types when ALL of the checked box type are unchecked:
$("input:checkbox").on("change", function() {
// get the name attribute
var nameAttr = $(this).prop("name");
// check how many checkbox inputs of that name attribute are checked
var checkedLength = $("input:checkbox[name=\"" + nameAttr + "\"]:checked").length;
// if 0, display other checkbox inputs, else if 1 hide all of the rest
if(checkedLength == 0) {
$("input:checkbox[name!=\"" + nameAttr + "\"]").parent().show();
}else if(checkedLength == 1) {
$("input:checkbox[name!=\"" + nameAttr + "\"]").parent().hide();
}
});
Overwhelmed by choice! Here's a plain JS version that just disables members of the non–selected groups.
I think that's better than hiding them so users can see the other options after they've selected one. Otherwise, to see the other options again, they must deselect all checkboxes in the group.
Note that div is a parent of the inputs, the listener passes a reference to the element and the related event object, modify as required.
<script>
function doStuff(div, evt) {
var checked, el, group, j, inputs, name, re;
var t = evt.target || evt.srcElement;
if (t.nodeName && t.nodeName.toLowerCase() == 'input' && t.type == 'checkbox') {
inputs = div.getElementsByTagName('input');
name = t.name;
// Set checked to true if any input with this name is checked
group = document.getElementsByName(name);
j = group.length;
while (j-- && !checked) {
checked = group[j].checked;
}
// Loop over inputs, hide or show depending on tests
for (var i=0, iLen=inputs.length; i<iLen; i++) {
el = inputs[i];
// If name doesn't match, disable
el.disabled = checked? (el.name != name) : false;
}
}
}
</script>
<div onclick="doStuff(this, event)">
<div>A1 <input type='checkbox' name='A[]' value='A1'></div>
<div>A2 <input type='checkbox' name='A[]' value='A2'></div>
<div>A3 <input type='checkbox' name='A[]' value='A3'></div>
<div>B1 <input type='checkbox' name='B[]' value='B1'></div>
<div>B2 <input type='checkbox' name='B[]' value='B2'></div>
<div>C1 <input type='checkbox' name='C[]' value='C1'></div>
</div>
Thanks guys, especially dbaseman (get me ideal) :
ok, Here is my code after referring from you all.
$("input[type=checkbox]").on("click", function() {
var sta = $(this).is(":checked"); sta=(sta==true?1:0);
if(sta==1){
var thisName = $(this).prop("name"); thisName=thisName.replace("[]","");
$("div input[type=checkbox]:not([name^=" + thisName + "])").parent().hide();
}else{
var num = $("[type=checkbox]:checked").length;
if(num==0){
$("div input[type=checkbox]").parent().show();
}
}
});
so far code able is performing as what i need.
Ps: i am still weak on jquery travelling part
Ps: Edited on re-opening all checkboxes part
Thanks once again!

Categories

Resources