How to append input value with ,(comma) when li click? - javascript

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!

Related

How to get the number of input tags containing certain text?

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/

How to change the function to limit its action to the id, class or selector

I have a function written in jquery that copies the value of the checkbox to the textarea #msg
$(document).ready(function(){
$("input:checkbox").click(function() {
var output = "";
$("input:checked").each(function() {
output += $(this).val() + "";
});
$("#msg").val(output.trim());
});
});
Clicking any checkbox on side copies of its value to the #msg field
How to reduce this effect that only checkboxes in the <ul> or a selected div operate in such a manner?
I want this:
<ul>
<input name="foo2" type="checkbox" value="Hello" id="tel_1">
<label for="tel_1">Hello</label>
</ul>
To be copied to the #msg textarea and this :
<input name="foo" value="123123123" id="tel_11" type="checkbox">
<label for="tel_11">Alan</label>
Not to be copied. I played with this :
$("input:checkbox").click(function()
And changed input:checkbox to ul:input:checkbox but I do not want to work.
You could use the id :
$(document).ready(function(){
$("#tel_1").click(function() {
var output = "";
output += $(this).val() + "";
$("#msg").val(output.trim());
});
});
Or if you want to exclude just #tel_11 you could use :not() selector like :
$(document).ready(function(){
$("input:checkbox:not('#tel_11')").click(function() {
var output = "";
$("input:checked:not('#tel_11')").each(function() {
output += $(this).val() + "";
});
$("#msg").val(output.trim());
});
});
Update :
If you have several id's as you sain in the comment (answers example) you could use start with selector like $("[id^='answer_'") ans that will include all of your 18 answers, e.g :
$(document).ready(function(){
$("[id^='answer_'").click(function() {
var output = "";
output += $(this).val() + "";
$("#msg").val(output.trim());
});
});
Hope this helps.
Use a selector that just matches checkboxes that are children of <ul>.
$("ul > :checkbox").click(function() {
...
});

Finding exact text in <li> with the inputted value

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

Search through list items on every input key press using jQuery and hide other item

I have code of list item , I want to search items using textbox how i can perform:-
Pricerange.Append("<ul>");
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Pricerange.Append(
"<li><span class='pull-left'><a href='default.aspx?Price=" +
ds.Tables[0].Rows[i]["Max_id"] + "' >" + ds.Tables[0].Rows[i]["Max_Price"] +
"</a></span> <span class='counter-pro pull-right'>12</span></li>");
}
Pricerange.Append("</ul>");
divpricerange.InnerHtml = Pricerange.ToString();
See This Image
- on left hand side in refine search i want to perform autocomplete action and hide other listitem.
You could use jQuery :contains selector to search the list and then show/hide list items based on the search result.
Here is a quick snippet that would give you an idea:
Demo Fiddle: http://jsfiddle.net/mwdune35/1/
/* jQuery code to search and reveal */
$("#txt").on("keyup", function() {
var srchTerm = $(this).val(),
$rows = $("#lst").children("li");
if (srchTerm.length > 0) {
$rows.stop().hide();
$("#lst").find("li:contains('" + srchTerm + "')").stop().show();
} else {
$rows.stop().show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Your HTML -->
<input id="txt" type="text" />
<br />
<ul id="lst">
<li>JM Aroma</li>
<li>Red Square Bonanza</li>
<li>Skylabs Special</li>
<li>Society Someplace</li>
<li>Anywhere</li>
<li>Everywhere</li>
<li>Nowhere</li>
<li>Somewhere</li>
</ul>
Kindly check this post
It uses Tables instead of list, but you can play with it.
$.each($("#table tbody").find("tr"), function() {
if($(this).text().toLowerCase().indexOf($(_this).val().toLowerCase()) == -1)
$(this).hide();
else
$(this).show();
})
In this way this script will executed thanks # abhitalks for valuable suggestion..
$(document).ready(function () {
$("#txt").on("keyup", function () {
var srchTerm = $(this).val(),
$rows = $("#lst").children("li");
if (srchTerm.length > 0) {
$rows.stop().hide();
$("#lst").find("li:contains('" + srchTerm + "')").stop().show();
} else {
$rows.stop().show();
}
});
});

jQuery adding search (ajax, perhaps?) filter to look through spans with prefix

I'm building an icon library where the user on the front end (submitting a form) can select an icon. I managed to get everything working as far as the selection process. Now, the final product will have over 400 icons, and i wanted to add a search (ajax, i guess) or autocomplete input where the user can type a couple of letters and it filter's out those icons.
They search will be filtering out some with a class that has the prefix "icon-".
I started on jsFiddle here: http://jsfiddle.net/yQMvh/28/
an example would be something like this :
http://anthonybush.com/projects/jquery_fast_live_filter/demo/
My HTML Markup:
<div class="iconDisplay">Display's selected icon</div>
<span id="selectedIcon" class="selected-icon" style="display:none"></span>
<button id="selectIconButton">Select Icon</button>
<div id="iconSelector" class="icon-list">
<div id="iconSearch">
<label for="icon-search">Search Icon: </label>
<input type="text" name="icon-search" value="">
</div>
<span class="icon-icon1"></span>
<span class="icon-icon2"></span>
<span class="icon-icon3"></span>
<span class="icon-icon4"></span>
<span class="icon-icon5"></span>
<span class="icon-icon6"></span>
<span class="icon-icon7"></span>
<span class="icon-icon8"></span>
</div>
JS (note: this includes the selection jQuery as well):
var iconVal = $(".icon_field").val();
$('#selectedIcon').addClass(iconVal);
$("#selectIconButton").click(function () {
$("#iconSelector").fadeToggle();
});
$("#iconSelector span").click(function () {
selectIcon($(this));
});
function selectIcon(e) {
var selection = e.attr('class');
$(".icon_field").val(selection);
$("#iconSelector").hide();
$('#selectedIcon').removeClass();
$('#selectedIcon').addClass(selection).show();
return;
}
Will this work for you? http://jsfiddle.net/yQMvh/37/
I've modified your input field slightly (added an id)
<input type="text" id="txt-icon-search" name="icon-search" />
and added this bit of code.
/**
* Holds information about search. (document later)
*/
var search = {
val: '',
icons: function (e) {
// get all the icons.
var icons = $('span[class*="icon-"]');
// assign the search val. (can possibly use later)
search.val = $(e.currentTarget).val();
// let the looping begin!
for (var i = 0, l = icons.length; i < l; i++) {
// get the current element, class, and icon after "icon-"
var el = $(icons[i]),
clazz = el.attr('class'),
iconEnd = clazz.substr(5, clazz.length);
// was the value found within the list of icons?
// if found, show.
// if not found, hide.
(iconEnd.indexOf(search.val) === -1) ? el.hide() : el.show();
}
}
};
$('#txt-icon-search').keyup(search.icons);
One possible way could be to use DataTables, this framework includes a search functionality, its row based tho, could be modified probably. Or if you want to present each icon with some facts like size, name, creator, it would be good maybe. The user could then sort the height etc.
Have a look here
Its a bit heavy weight but have a lot of possibilities for optimization
What you're looking for is something like this: http://jqueryui.com/autocomplete/
Pretty easy and all ready to use. You could pre-populate the available tags with your icons selection. Quick example:
$(function() {
var availableTags = [
"icon-name1",
"icon-name2",
"icon-name3",
"etc."
];
$( "input[name=icon-search]" ).autocomplete({
source: availableTags
});
});
EDIT: of course you can do something much more sophisticated, like displaying a thumbnail/preview of your icon next to each result
EDIT2:
From the sample in your link, I quickly threw something together to have it the way you wanted it:
JSCODE:
<script>
$(function() {
$.expr[':'].Contains = function(a,i,m){
return ($(a).attr("data-index") || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;
};
function listFilter(header, list) {
$("input.filterinput")
.change( function () {
var filter = $(this).val();
if(filter) {
$(list).find("span:not(:Contains(" + filter + "))").parent().slideUp();
$(list).find("span:Contains(" + filter + ")").parent().slideDown();
} else {
$(list).find("li").slideDown();
}
return false;
})
.keyup( function () {
$(this).change();
});
}
$(function () {
listFilter($("#iconSearch"), $("#list"));
});
});
</script>
Your html code tweaked a little:
<div id="iconSelector" class="icon-list" style="display: block;">
<div id="iconSearch">
<label for="icon-search">Search Icon: </label>
<input type="text" name="icon-search" class="filterinput" value="">
</div>
<ul id="list">
<li><span class="icon-icon1" data-index="red"></span></li>
<li><span class="icon-icon2" data-index="yellow"></span></li>
<li><span class="icon-icon3" data-index="blue"></span></li>
</ul>
</div>
Now if you type "red" you'll get the first span since the search is looking for a match from the data-index attribute. You can replace those with "Facebook", "Twitter", or whatever the name of your icon is.
If you want to directly search from the class name you can do something like this then:
<script>
$(function() {
$.expr[':'].Contains = function(a,i,m){
return ($(a).attr("class") || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;
};
function listFilter(header, list) {
$("input.filterinput")
.change( function () {
var filter = "icon-" + $(this).val();
if(filter) {
$(list).find("span:not(:Contains(" + filter + "))").parent().slideUp();
$(list).find("span:Contains(" + filter + ")").parent().slideDown();
} else {
$(list).find("li").slideDown();
}
return false;
})
.keyup( function () {
$(this).change();
});
}
$(function () {
listFilter($("#iconSearch"), $("#list"));
});
});
</script>

Categories