I have a list of words
<li>name</li>
<li>myname</li>
<li>yourname</li>
and i have an input box input type="text" value="name" id="the_value" with the value of "name" and a submit button with the id "submit_me". What is the exact code for this.
$("#submit_me").click(function(){
var ans = $("#the_value").val();
var list_item = //list items that will match the inputted value;
if(ans == list_item){
list_item.css("color","blue");
}
else{
alert("No word found on list item");
}
})
for the output, the list item with the value "name" will be in color blue.
Use .contains() if you don't want an exact match.
https://api.jquery.com/contains-selector/
Get the value from the input. Select the list items using contains.
If you need an exact match, pseudo code:
$('li').filter(() => $(this).text('THE EXACT TEXT'))
You can loop through the objects using .each() and compare contents using .text():
$("#submit_me").click(function(){
var found = false;
var ans = $("#the_value").val()
$("#list_items li").each( function(){
if( $(this).text() == ans ){
$(this).css("color","blue");
found = true;
}
});
if ( found == false ){
alert("No word found on list item");
}
});
Expects HTML like:
<ul id="list_items">
<li>name</li>
<li>myname</li>
<li>yourname</li>
</ul>
<input type="text" name="the_value" id="the_value" />
<button id="submit_me">Submit</button>
See fiddle here: https://jsfiddle.net/29ee12dj/
Loop through each li using each() and then change the color if the desired text is found.
$("#submit_me").click(function() {
var ans = $("#the_value").val(),
list_item;
$('li').each(function() {
if ($(this).text() == ans) {
list_item = $(this);
}
});
if (list_item) {
list_item.css("color", "blue");
} else {
alert("No word found on list item");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>name</li>
<li>myname</li>
<li>yourname</li>
</ul>
<input type="text" value="name" id="the_value">
<input type="button" id="submit_me" value="Click"/>
Related
I have two checkboxes. When I check one, the code will get status and id of that checkbox and push into array, if that value is not present already
The array set become like this
[8,0] [10,0]
Requirements:
It is inserting [8,0] [8,0] twice if I check and then uncheck and again check it so this should not insert multiple times same values
Remove specific array from set of array so if I uncheck chkecbox then remove only [8,0] but keep [10,0]
var positions = [];
$("body").on('click', '.check_box', function() {
var id = $(this).attr('data-id');
var status = $(this).attr('data-status');
if ($(this).prop("checked") == true) { // if click on check
if (!$.inArray(id, positions)) positions.push(id); // if id and status not in array then only push
positions.push([id, status]); // it will insert like [8,10] but geting duplicate [8,10] [8,10]
console.log(positions);
} else {
// if uncheck checkbox
// remove specific value like [8,0] or if value present [10,0] then remove this
console.log(positions);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="check_box" data-id="8" data-status="0">
<input type="checkbox" class="check_box" data-id="10" data-status="0">
You can use indexOf to check if object is present in array & add only if it doesn't exist
For removing, you can use filter & select only those objects in array which are not exactly as you specify
var positions = [];
$("body").on('click', '.check_box', function() {
var id = $(this).attr('data-id');
var status = $(this).attr('data-status');
if ($(this).prop("checked") == true) {
var exists = false;
positions.forEach((p) => {
if (id == p[0] && status == p[1]);
exists = true;
});
if (!exists) {
positions.push([id, status]);
}
} else {
positions = positions.filter(function(a) {
return !(a[0] == id && a[1] == status);
});
}
console.log(positions);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="check_box" data-id="8" data-status="0">
<input type="checkbox" class="check_box" data-id="10" data-status="0">
Explanation
In The first loop .each we iterate through each existing values in array & set exist to true when we find an element which has id & status same as the one we selected
If after loop we have exist as true, we know it already exists & we won't push it to array, otherwise we will push it to the array
In else condition we have used filter function of array, this fuction filters the array & only keep the elements for which we returned true, for elements we return false, it gets removed from resulting array
So we did check every element of array for exact match of id & status & if its matched we return false, so it gets removed from the resulting array
I will use findIndex and splice to handle it, hope this can help you :)
$(function() {
let positions = [];
$("body").on('click', 'input:checkbox', function() {
let id = $(this).attr('data-id');
let status = $(this).attr('data-status');
let data = [id, status];
if ($(this).is(':checked')) {
positions.push(data);
} else {
let index = positions.findIndex(c => c[0] === id);
if (index != -1)
positions.splice(index, 1);
}
$('#result').html(positions.toString());
});
});
#result{
width: 20rem;
height: 1rem;
margin-top: 2rem;
border-width:3px;
border-style:dashed;
border-color:#FFAC55;
padding: 15px 20px;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input type="checkbox" data-id="A" data-status="0">A</button>
<input type="checkbox" data-id="B" data-status="0">B</button>
<div id="result"></div>
</body>
</html>
If the array is small, just recreate it each time
let positions;
$("body").on('click', '.check_box', function() {
positions = [];
$(".check_box:checked").each(function() {
positions.push([
$(this).data('id'), $(this).data('status')
]);
});
console.log(positions);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="check_box" data-id="8" data-status="0">
<input type="checkbox" class="check_box" data-id="10" data-status="0">
My goal is to flag when a user enters the same text into one input that matches at least one other input's text. To select all of the relevant inputs, I have this selector:
$('input:text[name="employerId"]')
but how do I select only those whose text = abc, for instance?
Here is my change() event that checks for duplicate text among all the inputs on the page. I guess I am looking for something like :contains but for text within an input.
var inputsToMonitorSelector = "input[type='text'][name='employerId']";
$(inputsToMonitorSelector).change(function() {
//console.log($(this).val());
var inputsToExamineSelector = inputsToMonitorSelector
+ ":contains('" + $(this).val() + "')";
console.log(inputsToExamineSelector);
if($(inputsToExamineSelector).length > 1) {
alert('dupe!');
}
});
Or is there no such selector? Must I somehow select all the inputsToMonitorSelector's and, in a function, examining each one's text, incrementing some local variable until it is greater than one?
With input you need to use [value="abc"] or .filter()
$(document).ready(function() {
var textInputSelector = 'input[type="text"][name="employerId"]';
$(textInputSelector).on('input', function() {
$(textInputSelector).css('background-color', '#fff');
var input = $(this).val();
var inputsWithInputValue = $(textInputSelector).filter(function() {
return this.value && input && this.value == input;
});
var foundDupe = $(inputsWithInputValue).length > 1;
if(foundDupe) {
console.log("Dupe found: " + input);
$(inputsWithInputValue).css('background-color', '#FFD4AA');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="employerId" value="abc">
<input type="text" name="employerId" value="">
<input type="text" name="employerId" value="">
<input type="text" name="employerId" value="">
[value="abc"] means if the value is abc
[value*="abc"] * means if the value contains abc
[value^="abc"] ^ means if the value starts with abc
[value$="abc"] $ means if the value ends with abc
Note: :contains() not for inputs , and word text not used with inputs and <select>.. inputs and <select> has a value
In your case .. instead of using
$(inputsToExamineSelector).length > 1)
You may need to use .filter()
$(inputsToExamineSelector).filter('[value*="abc"]').length > 1)
OR
$('input[type="text"][name="employerId"]').filter(function(){
return this.value.indexOf('abc') > -1
// for exact value use >> return this.value == 'abc'
}).length;
And to use a variable on it you can use it like
'[value*="'+ valueHere +'"]'
Something like this works. Attach isDuplicated(myInputs,this.value) to a keyup event listener attached to each input.
var myInputs = document.querySelectorAll("input[type='text']");
function isDuplicated(elements,str){
for (var i = 0; i < myInputs.length; i++) {
if(myInputs[i].value === str){
myInputs[i].setCustomValidity('Duplicate'); //set flag on input
} else {
myInputs[i].setCustomValidity(''); //remove flag
}
}
}
Here's another one. I started with vanilla js and was going for an answer like Ron Royston with document.querySelector(x) but ended up with jquery. A first attempt at several things but here you go:
$("input[type='text']").each(function(){
// add a change event to each text-element.
$(this).change(function() {
// on change, get the current value.
var currVal = $(this).val();
// loop all text-element-siblings and compare values.
$(this).siblings("input[type='text']").each(function() {
if( currVal.localeCompare( $(this).val() ) == 0 ) {
console.log("Match!");
}
else {
console.log("No match.");
}
});
});
});
https://jsfiddle.net/xxx8we6s/
I have the following validation script I'm trying to get working:
function validate(id){
// checks only inputs with type "text" inside div id-calc
// e.g #haveprice-calc or #dontknow-calc
var input = $("." + id + "-calc input[type='text']").val();
if (input == ""){
alert("You must fill in all items on the form");
}
}
It is passed an ID (the ID is a div that wraps around these specific elements) and then I would like it to check every input of type text within the div=ID
At present, this code works only for the first input in the HTML. If it's unfilled, the alert appears. Once you fill it, the alert will no longer appear. But it doesn't then check the NEXT text input in the DOM.
Some example HTML
<div class="dontknow-calc">
<label>My materials cost</label><input type="text" name="materialcost" id="materialcost" /><br />
<label>My packing materials cost</label><input type="text" name="packingmaterialcost" id="packingmaterialcost" /><br />
<div class="btn btnCalc" id="dontknow">Calculate</div>
</div>
I expect it needs a foreach loop to run through every text element but I'm not sure how.
JSFiddle
Try this:
function validate(id){
// checks only inputs with type "text" inside div id-calc
// e.g #haveprice-calc or #dontknow-calc
var div = $("." + id + "-calc");
$(div).find("input[type = 'text']").each(function() {
if(this.value == "") {
alert("You must fill in all items on the form");
return false;
}
});
}
You can use .each() for this:
function validate(id)
{
$("." + id + "-calc input[type='text']").each(function()
{
if (this.value == "")
{
alert("You must fill in all items on the form");
return false;
}
});
}
I think what you are trying to do is to give an alert if any of the input fields are empty, in that case use .filter() to find out if any of the inputs are empty if any input is empty then show the alert
$(".btnCalc").click(function() {
var id = this.id;
var valid = validate(id);
console.log(valid)
});
function validate(id) {
// checks only inputs with type "text" inside div id-calc
// e.g #haveprice-calc or #dontknow-calc
var $empties = $("." + id + "-calc input[type='text']").filter(function() {
//may also use .trim() like !this.value.trim();
return !this.value
});
if ($empties.length) {
alert("You must fill in all items on the form");
return false;
}
return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="dontknow-calc">
<label>My materials cost</label>
<input type="text" name="materialcost" id="materialcost" />
<br />
<label>My packing materials cost</label>
<input type="text" name="packingmaterialcost" id="packingmaterialcost" />
<br />
<div class="btn btnCalc" id="dontknow">Calculate</div>
</div>
<br />
<br />
<div class="haveprice-calc">
<label>My other field</label>
<input type="text" name="materiotherfieldalcost" id="otherfield" />
<br />
<div class="btn btnCalc" id="haveprice">Calculate</div>
</div>
Or you could use the jQuery.Validation plugin (see http://jqueryvalidation.org/category/methods/ for some examples), and then use something like this:
$( "#myform" ).validate({
rules: {
field1: {
required: true
}
field2: {
required: true
}
// etc...
}
});
if you want to use each loop you can write some code like this:
$("." + id + "-calc input[type='text']").each(function(index,val){
// for current item value
console.log(val); // to see what's in the val argument
current_item_value = val.value;
});
I hope it helps
so i'm making this code that when the user searches for a query in a textbox, it will highlight the query somewhere in the content and focuses on the first occurence of that query. Problem is that when the user types in something like li or div which are HTML tags, those also appear as search results. For example, here is my html markup
<div class="col-lg-6" id="search-area">
<div class="input-group">
<input type="text" id="search-term" class="form-control">
<span class="input-group-btn">
<button id="search-button" class="btn btn-default"><span class="glyphicon glyphicon-search"></span></button>
</span>
</div><!-- /input-group -->
</div>
<h3>Did we miss something? Have any more FAQs to add? Contact us directly at blabla#gmail.com</h3>
and here is my js
function searchAndHighlight(searchTerm, selector) {
if(searchTerm) {
var selector = selector || "#mainContainer";
var searchTermRegEx = new RegExp(searchTerm,"ig");
var matches = $(selector).text().match(searchTermRegEx);
if(matches) {
$('.highlighted').removeClass('highlighted'); //Remove old search highlights
$(selector).html($(selector).html()
.replace(searchTermRegEx, "<span class='highlighted'>"+searchTerm+"</span>"));
if($('.highlighted:first').length) { //if match found, scroll to where the first one appears
$(window).scrollTop($('.highlighted:first').position().top);
}
return true;
}
}
return false;
}
$(document).ready(function() {
$('#search-button').on("click",function() {
if(!searchAndHighlight($('#search-term').val())) {
alert('No results found for query "'+$('#search-term').val()+'".');
}else{
alert($("span[class='highlighted']").length);
}
});
$("#search-term").keypress(function(event) {
if (event.which == 13) {
if(!searchAndHighlight($('#search-term').val())) {
alert('No results found for query "'+$('#search-term').val()+'".');
}else{
alert($("span[class='highlighted']").length);
}
}
});
});
if the user inputs h3 for example, the result will be
<**h3**>Did we miss something? Have any more FAQs to add? Contact us directly at blabla#gmail.com</**h3**>
shouldn't it say that there are no results found?
Try to change you code to interate over all the children nodes and check their val() instead of their html():
....
var selector = selector || "#mainContainer";
var searchTermRegEx = new RegExp(searchTerm,"ig");
var matches = [];
$.each($(selector).children(), function(index, item){
matches.push($(item).val().match(searchTermRegEx));
});
if(matches) {....
i have HTML like below,
<ul class="holder" style="width: 512px;">
<li id="pt_5uZqW99dmlgmiuCTJiPHDC9T9o2sfz0I"
rel="test1#gmail.com"
class="bit-box">test1#gmail.com
</li>
<li id="pt_9O0pMJDhtNbRgU1vNM8He8Vh9zpJ1tcE"
rel="test2#gmail.com"
class="bit-box">test2#gmail.com<a href="#"
class="closebutton"></a>
</li>
<li id="pt_U8JH5E9y5w4atm4CadEPvuu3wdh3WcBx"
rel="test3#gmail.com"
class="bit-box">test3#gmail.com<a href="#"
class="closebutton"></a></li>
<li id="Project_update_user_id_annoninput"
class="bit-input">
<input type="text" autocomplete="off" size="0" class="maininput"></li>
</ul>
<input id="removeuser" value="" />
I need to store the values of li's in hidden input box when I click that li's.
If I click first two li's i need to store the values like,
<input id="removeuser" value="test1#gmail.com,test2#gmail.com" />
That is i need to append input values every time when i click li's.
i used below one,
jQuery(document).ready(function(){
jQuery("a.closebutton").click(function(){
jQuery("input#removeuser").val(jQuery.map(jQuery(this).parent().attr('rel')).join(","));
});
});
But it does not works.how can i do that?
http://jsfiddle.net/ySV6F/
jQuery(document).ready(function(){
jQuery("a.closebutton").click(function(){
jQuery("input#removeuser").val(jQuery("input#removeuser").val() + "," + jQuery(this).parent().attr('rel'));
$(this).remove();
return false;
});
});
This fiddle fixes your issue: http://jsfiddle.net/pratik136/zVmwg/
First change I did was move your text within the <a /> tags. This allowed you to click on them as expected.
Next, I changed the JS to:
jQuery(document).ready(function() {
jQuery("a.closebutton").click(function(a) {
var v = jQuery(this).parent().attr('rel');
var t = jQuery("input#removeuser").val();
if (t.indexOf(v) < 0) {
if(t.length>0){
t += ",";
}
jQuery("input#removeuser").val(t + v);
}
});
});
I addded the additional check to ensure no duplicates are entered, and that a comma is appended only when necessary.
Try:
var arr = [];
$(".closebutton").click(function(e) {
e.preventDefault();
var email = $(this).parent("li").attr("rel");
if( $(this).hasClass("added") ) {
arr= $.grep(arr, function(value) {
return value != email;
});
$(this).removeClass("added");
}
else {
arr.push( email );
$(this).addClass("added");
}
$("input[id='removeuser']").val( arr.join(",") );
});
First I would suggest that instead of using rel attribute (which has a specific meaning in (X)HTML with certain tags) you use html safe data-* attributes
like this:
<li id="pt_5uZqW99dmlgmiuCTJiPHDC9T9o2sfz0I" data-email="mdineshkumarcs#gmail.com"
class="bit-box">mdineshkumarcs#gmail.com</li>
To access this attribute just use jQuery $(elem).attr('data-email')
Now the solution with no duplicates:
jQuery(document).ready(function(){
jQuery("a.closebutton").click(function(){
var value = $(this).parent().attr('data-email');
var values = $("input#removeuser").val().split(',');
var is_in = false;
// already in?
$.each(values, function(i, e){
if(e == value) {
is_in = true; return false; // set and exit each
}
});
if (!is_in) {
values.push(value);
$("input#removeuser").val(values.join(','));
}
return false;
});
})
I've put the working code on jsFiddle so that you can see it in action.
jQuery(document).ready(function(){
jQuery("a.closebutton").bind('click', function(){
var data = $(this).parent().attr('rel');
if($("#removeuser").val() == ""){
$("#removeuser").val(data);
} else {
$("#removeuser").val(", "+data);
}
$(this).parent().hide();
});
});
Here I'm removing the li once clicked. You may I believe use the .toggle() function to enable users to remove a value from #removeuser as well.
Hope this helps!