Remove string from input on click? jQuery - javascript

I'm trying to write my own function to wrap each string separated by a comma in a tag, I have this working, but on the 'close' click id like to remove the corresponding string from the input, is this possible at all?
jQuery
$('body').on('click', '.tag span', function(){
$(this).parent().hide();
});
$('input').keyup(function(e) {
$('.result').html('');
var valueArr = $(this).val().split(',');
for(var i=0; i<valueArr.length; i++){$('.result').append('<div class="tag">'+valueArr[i]+'<span> X</span></div>')};
});
http://jsfiddle.net/Liamatvenn/7huQ4/1/

Try this:
$('body').on('click', '.tag span', function(){
$(this).parent().hide();
$(this).closest('.result').prev('input').val(""); //get the input respective to the clicked close button.
});
.closest() will get you to the parent .result and target only its previous input which generated the tag using .prev().
Demo
Much simpler, use index of the clicked tag item and remove that respective item from the array based on the same index as they are inserted in that order itself.
$('body').on('click', '.tag span', function () {
var $parent = $(this).closest('.tag');
var index = $parent.index(); //Get the index of the `tag`
$(this).closest('.result').prev('input').val(function (_, value) { //use val function argument
var values = value.split(','); //split the value
values.splice(index, 1); //remove the item from array
return values.join(','); //join them back
});
$parent.remove(); //then remove your tag
});
Demo

You could always modify your click handler to do something like:
$('body').on('click', '.tag span', function(){
var $this, $input, val, arr;
$this = $(this);
$input = $('input');
arr = $input.val().split(',');
val = $this.parent().text().replace(' X','');
arr.splice(arr.indexOf(val), 1);
$input.val(arr.join(','));
$this.parent().hide();
});
You can see it working at http://jsfiddle.net/eF5ev/

You can just store your elements in an array and remove the ones that get clicked by their index:
var $tag = $('<div class="tag"><span class="text"></span><span class="close">×</span></div>');
var tags = [];
$('.result').on('click', '.tag .close', function() {
var $parent = $(this).parent();
tags.splice($parent.index(), 1);
$parent.remove();
$('input').val(tags.join(', '));
});
$('input').keyup(function() {
tags = []
$('.result').empty();
$(this.value.split(/\s*,\s*/)).each(function(index, value) {
var tag = $tag.clone();
tag.find('.text').text(value);
tag.appendTo('.result');
tags.push(value);
});
});
Demo: http://jsfiddle.net/7huQ4/9/

You can input data on close button click. jquery text() method to get text inside tag.
remove that text from input data. then remove leading and trailing commas with regular expression.
Try this one.
$('input').keyup(function(e) {
var input = $(this); /* Store input object for replaced value insertion */
$('.result').html('');
var valueArr = $(this).val().split(',');
for (var i = 0; i < valueArr.length; i++) {
$('.result').append('<div class="tag">' + valueArr[i] + '<span> X</span></div>');
}
$('span').click(function() {
/* Removal of unwanted string like ' X' (close button) */
var data = $(this).parent().text();
data = data.replace($(this).text(), ""); /* Basic javascript replace() function*/
/* Delete unwanted commas, Store modified string to input field */
input.val(input.val().replace(data, '')
.replace(/^[,\s]+|[,\s]+$/g, '')
.replace(/,[,\s]*,/g, ','));
});
});
demo : http://jsfiddle.net/7uqEg/

Related

how to get value from textbox on click of button in jquery

enter image description here
this is the image, in this, i have a button when I click the button it should show me the updated value of textbox into the alert box. I have coded something like this.
$(document).on('click', '#Button1', function () {
var newStr = document.getElementsByName('input');
var str = '';
for (var i = 0; i < newStr.length; i++)
{
str = str + newStr.item(i).value;
}
alert(str);
});
But things are not working properly. Need help thanxx.
$(document).on('click', '#table1 tr', function () {
var tableData = $(this).children("td").map(function () {
return $(this).text();
}).get();
$(tableData).each(function (index, value) {
$('#txt' + index).val(value);
});
});
this is sending table data to the textbox. I just want to get all the value of textbox into one variable and want to check that value for further process.
you haven't gave your html. but using this you can access all your input type.
$("#formID :input").each(function(){
var input = $(this);
});
or IF u want to access only input type = text
use
$("#formID input[type=text]")
Hope this will help you out

Show a number of additional divs on every click

I want to have a sequential list display, where initially all the lis except the first one are hidden, and when the user clicks a button, the lis appear by groups of 3. Eventually I would like to hide the button when the list gets to the end.
The code is something like this, but it shows only one per click, every third - but I want to show also the in-between elements until the third
jQuery(".event-holder:gt(0)").hide();
var i = 0;
var numbofelem = jQuery(".event-holder").length;
jQuery("#allevents").on('click', function(e){
e.preventDefault();
i+=3;
jQuery(".event-holder").eq(i).fadeIn();
if ( i == numbofelem ) { jQuery(this).hide(); }
});
Probably the .eq(i) is not the function I need, but couldn't find the correct one...
You can use :hidden with use of .each() loop:
jQuery("#allevents").on('click', function(e){
e.preventDefault();
jQuery(".event-holder:hidden").each(function(i){
if(i <= 2){
jQuery(this).fadeIn();
}
});
});
Working fiddle
If you have just three you could use :
jQuery(".event-holder:gt(0)").hide();
var i = 0;
var numbofelem = jQuery(".event-holder").length;
var li = jQuery(".event-holder");
jQuery("#allevents").on('click', function(e){
e.preventDefault();
li.eq(i+1).fadeIn();
li.eq(i+2).fadeIn();
li.eq(i+3).fadeIn();
i+=3;
if ( i == numbofelem ) { jQuery(this).hide(); }
});
If you have several lis to show you could use a loop, e.g :
var step = 10; //Define it outside of the event
for(var j=0;j<step;j++){
li.eq(i+j).fadeIn();
}
i+=step;
Hope this helps.
You eq(i) needs to be looped.
jQuery(".event-holder:gt(0)").hide();
var i = 0;
var numbofelem = jQuery(".event-holder").length;
jQuery("#allevents").on('click', function(e){
e.preventDefault();
//i+=3;
//jQuery(".event-holder").eq(i).fadeIn();//You are showing only the third element. Loop this
//Something like this
for(var j=i;j<i+3;j++){
jQuery(".event-holder").eq(i).fadeIn();
if ( i == numbofelem ) { jQuery(this).hide(); }
}
i = j;
});
An alternative approach would be to buffer all the items, and keep adding them until empty:
var holders = $('.event-holder').hide();
$("#allevents").click( function(e){
e.preventDefault();
holders = holders.not(holders.slice(0, 3).fadeIn());
if(holders.length === 0) $(this).hide();
});
Fiddle

In jquery how to put values of check-boxes which are ticked into an array?

I have check-boxes of "Apartment","House" etc. I want to collect the values of these check-boxes into an array and send that array to controller using json. Since I'm new to jquery I don't know how to put those values into an array using jquery ?
<script type="text/javascript">
$(document).ready(function () {
var arr = $("#hiddenroomdetails").val().split(",");
$('input[type=checkbox]').each(function () {
if ($.inArray($(this).val(), arr) > -1) {
$(this).attr("checked", "checked");
}
});
});
</script>
$.getJSON('#Url.Action("testcata", "home")' + '?property=' + selectedvalue +"&chkd="+checkedValues
function (data) {
//code
})
Pretty common way to do it using jQuery is by using map method. For example:
var checkedValues = $('.check:checked').map(function() {
return this.value;
}).get();
Demo: http://jsfiddle.net/mgzvm2s2/
Lets say if you give these checkboxes a class called "selectbox" and do the following code:
var selected = [];
$('.selectbox').click(function(){
if( $.inArray($(this).val(), selected) > -1 ){
var index = selected.indexOf( $(this).val() );
selected.splice( index, 1 );
}
else {
selected.push( $(this).val() );
}
}
This will fire an event when the checkboxes are clicked. It then checks if the value already exists in the "selected"-array. if it exists, it removes it (checkbox is unchecked). If it doesnt exist (checkbox is checked), it ads it.
Then you can pass on the "selected" array to the json function
You can try this:
$('button').click(function() {
var Arr = [];
$('.check:checked').map(function() {
Arr.push(this.value);
});
alert(Arr);
alert(Arr[0]);
})
Check jsfiddle.net

When click a button add value to textarea

<script type="text/javascript">
$(document).ready(function() {
$(".buttons").click(function(){
var cntrl = $(this).html();
$("#txt-area").text(cntrl+",");
//alert (cntrl);
});
});
</script>
When I click to my character on my html page character's value sets to textarea, but when I click to another character previous char disappears. I know about something about arrays in JS but how can I handle this.
How can I add values to textarea properly without disappearing?
Try
$(document).ready(function () {
$(".buttons").click(function () {
var cntrl = $(this).html();
$("#txt-area").val(function (_, val) {
return val + cntrl + ","
});
//alert (cntrl);
});
});
Demo: Fiddle
or
$("#txt-area").text($("#txt-area").val() + cntrl+",");
$("#txt-area").append(cntrl + ",");
Demo: Fiddle - I prefer using val() because I consider it as a input element
Arun's answer above works, but it will add a comma to the end. If you want to avoid that, place the comma before the new value, and then have the code check to see if this is the first time something is being added, and not place a comma that time.
$(document).ready(function () {
var oldvalue;
var newvalue;
$(".buttons").click(function () {
oldvalue = $("#txt-area").val(); //GET THE VALUE OF TEXTBOX WHEN USER CLICKS
if (oldvalue) {newvalue = ', '+$(this).html();} // IF THE TEXTBOX ISN'T BLANK, PLACE A COMMA BEFORE THE NEW VALUE
else {newvalue = $(this).html();} //IF THE TEXTBOX IS BLANK, DON'T ADD A COMMA
$("#txt-area").val(oldvalue + newvalue); //PLACE THE ORIGINAL AND NEW VALUES INTO THE TEXTBOX.
});
});
Try,
$(document).ready(function() {
$(".buttons").click(function(){
var cntrl = $(this).html();
var xTxtArea = $("#txt-area");
xTxtArea.text(xTxtArea.text() + cntrl + ",");
});
});

Using jQuery filter() to get all matched .val()

I have a number of textfields and I need to select the values of those textfields whose values are not equal to their title attribute.
Problem: With my attempt, the jQuery code below simply selects the value of the first matched textfield. How do I get all matched textfields' values?
jQuery Code
var inputs = $(".input").filter(function() {
return $(this).val() != $(this).attr('title');
}).val();
console.log(inputs);
Here is simpler solution:
var input = [];
jQuery('input[type=text]').each(function(){
if(jQuery(this).val() != jQuery(this).attr('title') ) {
input.push(jQuery(this).val());
}
});
The .val() method only returns the value of the first element in the selected list of elements. Try turning it into an array instead:
var inputs = $(".input").filter(function() {
return $(this).val() != $(this).attr('title');
}).map(function(){
return $(this).val();
}).get();
console.log(inputs);
Here's one way to do it:
var inputs = [];
$(".input").filter(function() {
return $(this).val() != $(this).attr('title');
}).each(function() {
inputs.push($(this).val());
});
console.log(inputs);
Example: http://jsfiddle.net/grc4/cCRfE/

Categories

Resources