How to remove extra commas from a list - javascript

I have a list of checkboxes and if one is checked, I'm appending the checkbox value to a input field elsewhere on the page. If a checkbox is unchecked, I'm removing the value from the hidden input field. What is happening is if the values are being added and removed just fine but they are leaving a series of commas behind when a check box is checked, unchecked, checked, unchecked, etc.
A) should I worry about it
B) if yes, how should I alter my add/append routine (see below) or is there a better way to do what I'm doing? I'd prefer to end up with a clean list like 0_1,0_2,41_4 opposed to 0_1,,,,,,,,,,,,,,,,0_2,,,,41_4,,,,.
<input type="text" value="0_1,0_2,41_4" id="EOStatus_SelLayers" />
// example of dataset: '0_1,0_2,41_4';
if ( xyz.hasClass("icon-check-empty") ) {
var existing_str = $('#EOStatus_SelLayers').val();
if (existing_str==null || existing_str==""){
//add
$('#EOStatus_SelLayers').val(id);
}
else {
//append
$('#EOStatus_SelLayers').val( existing_str + ',' + id);
}
}
else {
$(xyz).removeClass("icon-check").addClass("icon-check-empty");
var old_str = $('#EOStatus_SelLayers').val();
var new_str = old_str.replace(','+id,'');
var new_str = old_str.replace(id,'');
$('#EOStatus_SelLayers').val(new_str);
}
In the else statement, I could do something like this:
var new_str = old_str.replace(id,'');
var new_str = old_str.replace(',,',',');

You can replace the id with an empty string and then replace any extraneous commas.
There are three places you can end up with an extraneous comma:
A double comma somewhere in the middle (needs to be replaced with a single comma)
A leading comma (needs to be removed)
A trailing comma (needs to be removed)
You can address all three cases with these two replace operations:
.replace(/,,/g, ",").replace(/^,|,$/g, "");
Which in place could look like this:
else {
$(xyz).removeClass("icon-check").addClass("icon-check-empty");
var old_str = $('#EOStatus_SelLayers').val();
var new_str = old_str.replace(id,'').replace(/,,/g, ",").replace(/^,|,$/g, "");
$('#EOStatus_SelLayers').val(new_str);
}

If you're using jQuery - a simpler approach would be simple re-set the input value each time a change was made to checkboxes? Simply concat the ID of each :checked input... If you're using a custom lib to change the appearance of the checkboxes I'm sure there's on-change event triggers that would allow the following to work.
Alternatively you should be able to edit to suit your specific needs.
$('input[type=checkbox]').on('change', function(e) {
var newVal = [];
$('input[type=checkbox]:checked').each(function() {
newVal.push($(this).attr('id'));
});
$('#EOStatus_SelLayers').val(newVal.join(','));
});
Or, in the case you're using images:
$('[class^="icon-check"]').on('click', function(e) {
var newVal = [];
$('.icon-check').each(function() {
newVal.push($(this).attr('id'));
});
$(this).toggleClass('icon-check-empty');
$(this).toggleClass('icon-check');
$('#EOStatus_SelLayers').val(newVal.join(','));
});
Disclaimer: not tested - but looks like it should work.

Related

jQuery add/remove text from input string

I have a function that adds text into an input box. Basically you click a div and it activates the function by onclick="addvalue(“Name”)"
function addvalue(newdate){
var input = $("#datestobeexcluded");
input.val(input.val()+","+newdate);
};
But what I really need to do is to check the string inside the input value,
If it’s not there to add the text, which it does, and remove it if text is already present in string.
I am not doing well with jquery at the moment. Thank you in advance
var input = $("#datestobeexcluded");
if(input.val().search(newdate) >= 0)
{
input.val(input.val().replace(newdate,''));
}
else
{
input.val(input.val()+","+newdate);
}
And if you have multiple occurrences:
input.val(input.val().replace(/newdate/g,''));
You can use includes with RegExp:
var input = $("#datetobeexcluded");
input.val(input.val().includes(newdate) ? input.val().replace(new RegExp(newdate, "g"), "") : `${input.val()},${newdate}`);
You may replace your inline on click binding with jQuery styled click listener.
Then you may use the next code.
const $input = $('#your-input')
$('.extra-option').click(function() {
const inputString = $input.val()
const content = inputString ? inputString.split(',') : []
const stringToAdd = $(this).html()
const stringIndex = content.indexOf(stringToAdd)
if (stringIndex === -1) {
content.push(stringToAdd)
} else {
content.splice(stringIndex, 1)
}
$input.val(content.join(','))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="your-input" type="text" />
<div class="extra-option">Name</div>
<div class="extra-option">Company</div>
<div class="extra-option">Address</div>
At first, you need to figure out how you will provide clicked element value. Your approach is definitely wrong because you need to bind function on click, while you return undefined. For test purposes I use innerText.
At the second, you need to check if your string contains clicked div string or not. To simplify this logic, I use splitting by delimiter and then manage with an array of entries.
The last step, you need to update your input value.
I guess it's all.
Let me know if you have any question.

Javascript: Cannot move back in HTML Input

I have a form where a user can enter a URL but I wanted to have it automatically remove spaces.
To do this I have the following jQuery function:
$('#URL').on('change keyup', function() {
var sanitized = $(this).val().replace(' ', '');
$(this).val(sanitized);
});
But the problem with this code is that you cannot use the arrow keys to move in the input. i.e. if I type in http://oogle.com and I want to use arrow keys to fix my spelling mistake, it will automatically keep the cursor on the very last character. On top of this, I cannot use Ctrl+A to select all the text.
Is there a way to have jQuery/Javascript automatically remove spaces while still being able to move around the input or select it all?
Here is my jsFiddle showing my issue.
Use keypress instead of keyup, so only characters are caught. In this case, discard a space if it is pressed.
Also check for a paste event, and use a regular expression to replace all spaces. Change the value within a timeout in order to capture the pasted value:
$('#URL')
.on('keypress', function(e) {
if(e.which === 32) return false;
})
.on('paste', function() {
$self= $(this);
setTimeout(function() {
$self.val($self.val().replace(/\s/g, ''));
});
});
Fiddle
Fiddle
You can:
Record the cursor position
Execute your original code
Then restore the cursor position
Update:
Make sure to change your .replace to .replace(/\ /g, "")
Update 2 (cursor position):
This fixes the cursor position when inserting spaces.
For example copy and pasting the following will now work with any cursor position:
341 10365
34 1 1 03 65
First you need to get the string to the left of the cursor:
var leftString = $(this).val().substring(0, start);
Then you need to count the spaces in that string:
var leftSpaces = (leftString.match(/ /g) || []).length;
Then subtract leftSpaces from the start and end variables.
Javascript
$('#URL').on('change keyup', function() {
// Store cursor position
var start = this.selectionStart;
var end = this.selectionEnd;
// Check for newly inserted spaces
var leftString = $(this).val().substring(0, start);
var leftSpaces = (leftString.match(/ /g) || []).length;
newStart = start - leftSpaces;
newEnd = end - leftSpaces;
// Original Code
var sanitized = $(this).val().replace(/\ /g, "");
$(this).val(sanitized);
// Place cursor in correct position
this.setSelectionRange(newStart, newEnd);
});
Another option would be to add a delay after the keyup event
$('#URL').on('change keyup', function() {
delay(function(){
var sanitized = $('#URL').val().replace(' ', '');
$('#URL').val(sanitized);
}, 1000 );
});
http://jsfiddle.net/xv2e9bLe/
The usual way to adjust user input in a form is done when user finish their input or edit. It's pretty awkward to adjust user input on the fly. So, the onBlur event usually the best event to catch and sanitize a form input.
Based on the answer from adriancarriger, I use the 'blur' event which catch the user input after the user finish the input and do something else.
$('#URL').on('blur', function() {
var start = this.selectionStart,
end = this.selectionEnd;
var sanitized = $(this).val().replace(/\ /g, "");
$(this).val(sanitized);
this.setSelectionRange(start, end);
});
This should work well. If you have a real form submit, you can also catch the user input at onSubmit event of the form as well. Note that onSubmit happens at the form object, not the input object.

Disable button if a string is matched from a line in jquery

I'm trying to build a website using jquery-1.10.2 where I want to block css related strings like <style>, <link> etc. I want to disable the submit button if any of those strings match. So far I've managed to block them using .keyup() function but if I write more than those tags like <link rel="stylesheet" href="css/bootstrap.min.css"> then it won't work. Here are my codes,
$(document).ready(function () {
$('#inputdivEditor-2').keyup(function () {
var input = $(this).val();
if (input == "<style>" || input == "</style>" || input == "<link>") {
$('#deactivedivEditor-2').attr("disabled", "disabled");
}else{
$('#deactivedivEditor-2').removeAttr("disabled");
}
});
});
JSFiddle Demo
How can I disable the button if any of those strings match from any lines? Need this help badly. Thanks.
You can use regex to check if the text contains certain pattern.
$(document).ready(function () {
var regex = /<\/?style.*?>|<link.*?>/;
$('#inputdivEditor-2').keyup(function () {
var val = $(this).val();
$('#deactivedivEditor-2').prop('disabled', regex.test(val));
});
});
Demo: http://fiddle.jshell.net/tusharj/52xd3s11/
Regex
/ : Delimiters of regex
\/?: Matches 0 or 1 /
.*?: Matches any character any no. of times
|: OR in regex
You can use the following regex to match those strings.
var regex = /<(style|link)>/;
To disable update when the elements are present. That however wouldn't solve all cases. If someone wants he can bypass the regex by writing < style > or with using different encoding and so on.
In my opinion a better option is to look at the content from a browser's perspective. In other words take the input and make an element out of it:
var dummyElement = $('<div></div>');
dummyElement.html(input); //contents of the input field
if(dummyElement.find('style').length > 0) {
//you get the point
}
..because there's that one question on SO, which explains why not parse HTML with regexes..
RegEx match open tags except XHTML self-contained tags
Just use regex to check anything between < > like below:
DEMO
$(document).ready(function () {
$('#inputdivEditor-2').keyup(function () {
var input = $(this).val();
var regex=/<*>/;
if (regex.test(input)) {
$('#deactivedivEditor-2').attr("disabled", "disabled");
} else {
$('#deactivedivEditor-2').removeAttr("disabled");
}
});
});
You can use .prop('disabled',true) for disable button and .prop('disabled',false) for enable button. Both are used after $('#deactivedivEditor-2').
First of all, you can use regular expressions to check the string with a pattern at any position. The regexp I show below matches on anything between two angular braces - even non html tags too.
Secondly - it is a bit off topic - the best and recommended solution for setting and disabling the "disabled" attribute with jquery is by using the .prop() method
$(document).ready(function () {
$('#inputdivEditor-2').keyup(function () {
var inputValue = $(this).val();
var regexp = /]*?>/;
var isDisabled = regex.test(inputValue);
$('#deactivedivEditor-2').prop("disabled", isDisabled);
});
});

How to replace only the text of this element with jQuery?

I'm trying to make a kind of simple search engine, where
the user enters a string and if it's equal to the text inside
an element, that portion of text must be highlighted some way.
This is the html:
<input type="text">
<input type="button" value="Change text"><br>
Click here to get more info!
this is the css:
.smallcaps{
color:red;
}
and this is the jquery function that makes the search and replace:
$("input[type='button']").click(function(){
var textValue = $("input[type=text]").val();
$("a").html(function(_, html) {
return html.replace(new RegExp(textValue,"ig"), '<span class="smallcaps">'+textValue+'</span>');
});
});
This is an example of how it looks like:
Everything works fine, until the search string is equals to the name of a node element, so for example if the search string is a, the html will be broken.
How can I avoid the replace of the html itself?. I just want to work over the text.
This is the codepen:
http://codepen.io/anon/pen/mefkb
Thanks in advance!
I assume that you want to only highlight the last search and not store the ones from before.
With this assumption, you can store the old value if it is the first call and use the stored value in the calls afterwards:
$("input[type='button']").click(function(){
// Escape the html of the input to be able to search for < or >
var textValue = $('<div/>').text($("input[type=text]").val()).html();
if(textValue === '') return;
$("a").html(function(_, html) {
var old = $(this).data('content');
if(!old) {
old = html;
$(this).data('content', old);
}
var replacer = function(match) {
return match.replace(new RegExp(textValue, "ig"), '<span class="smallcaps">'+textValue+'</span>');
};
if(/[<>]/.test(old)) {
return old.replace(/^[^<>]*</gi, replacer).replace(/>[^<>]*</gi, replacer).replace(/>[^<>]*$/gi, replacer);
}
return replacer(old);
});
});
Also i fixed two bugs I found when testing:
if you search for an empty string, everything is broken.
If you search for html characters like < or > nothing is found as in the text they are converted to < or >.
One thing is not solved, as it is not possible to easily implement it without destroying the subelement structure: It is not possible to search in different subelements, as you have to remove the tags, search then and insert the tags at the right position afterwards.
Working fiddle: http://codepen.io/anon/pen/KlxEB
Updated Demo
A workaround would be to restore <a> to original text, instead of complicating the regex.
Your problem is a form the <span> tag is getting replaced.
var init = $("a").text(); //save initial value
$("input[type='button']").click(function(){
$('a').text(init); //replace with initial value
var textValue = $("input[type=text]").val();
$("a").html(function(_, html) {
return html.replace(new RegExp(textValue,"ig"), '<span class="smallcaps">'+textValue+'</span>');
});
});

Input Text format, Jquery, Javascript or Css

While Typing in a input First letter should change to Capital, But rest letters should be in lowercase, Even user Input capital letters it should changed it lowercase.
Example input word: mOuSe , ComPuTER
Important Point: While Typing it should change to: Mouse, Computer
I have tried many Stackflow soloution, But for above logic i found none.
Using Css: Click Here
Using Javacript: Click Here (This one worked but for last letter it doesnt works)
Any solution is accepted using Jquery, Javascript or Css
$(document).ready(function() {
//alert('ready');
$('input').on('keypress', function(event) {
var $this = $(this),
val = $this.val();
val = val.substr(0, 1).toUpperCase() + val.substr(1).toLowerCase();
$this.val(val);
});
});
Use the input event instead of the keypress event.
$('input').on('input', function(event) {
function initCap(t){
t.value=t.value.toLowerCase();
t.style='text-transform:capitalize;'
}
call the method onkeypress and onblur
Try This
$('input').on('keyup', function(event) {
var firstchar = $(this).val().substring(0,1);
var remainchar = $(this).val().substring(1,$(this).val().length).toLowerCase();
$(this).val(firstchar + remainchar);
});
$('input').on('keydown', function(event) {
var firstchar = $(this).val().substring(0,1);
var remainchar = $(this).val().substring(1,$(this).val().length).toLowerCase();
$(this).val(firstchar + remainchar);
});
DEMO
It might be interesting to point out that CSS text-transform: capitalize; only alters the display of the input, while Javascript modifies the actual HTML value. This matters if the input is, for example, a CAPTCHA response or form input field that needs to be validated.
With pure Javascript, you could split the input into separate words & transform each one of them, like so:
HTML
<div id="transform">mOuSE, cOmPUTEr</div>
<button type="button">Capitalize</button>
JS
var rgx = /,/; /* word splitter, can be anything */
var target = document.getElementById('transform');
document.getElementsByTagName('button')[0].onclick = function() {
var strArr = target.innerHTML.split(rgx); /* split the input */
for (var word = 0; word < strArr.length; word++) { /* iterate over each word */
strArr[word] = strArr[word].toLowerCase().trim();
var firstLetter = strArr[word].substr(0,1).toUpperCase();
var otherLetters = strArr[word].substr(1, strArr[word].length)
strArr[word] = firstLetter+otherLetters;
}
target.innerHTML = strArr.join();
}
Demo: http://jsbin.com/farib/2/edit
NB: If your input is in a <textarea> or <input>, replace .innerHTML with .value.
Try this css solution.
DEMO
input {
text-transform:capitalize;
color: blue;
}
$(document).ready(function(){
$("input").on("keypress",function(){
$(this).val($(this).val().toLowerCase());
});
})

Categories

Resources