jQuery add/remove text from input string - javascript

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.

Related

Adding JQuery Reference breaks tags input

I am using a template that comes with a nice Tags Input, but I now want to be able to count the number of words and limit the number of words based on certain criteria, however, the only way I've found to do this is by using keyup of the specific textboxfor, but to do this I need to reference to JQuery, but then it breaks my tags input. Below is what I currently have:
#Html.TextBoxFor(model => model.EmploymentSkills, new { #id = "tags", #class = "form-control tagsinput", #type = "text", #placeholder = "Add skill and press enter", data_role = "tagsinput" })
<script src="~/SmartAdmin/scripts/plugin/bootstrap-tags/bootstrap-tagsinput.min.js"></script>
Is there a way I can do this with out referencing to JQuery, or able to reference to it and not break my tags input ?
Is there something specific with data_roleattribute? As long as i remember you should put all attributes in # if using XPath. Try replacing data_role = 'tagsinput' to #data-role = 'tagsinput'. Maybe that is causing the issue.
So I found a solution to this. As mentioned above, the .keyup or .keydown didnt work, so I landed up using .change. This is the function I used, also counting the number of words and limiting them:
$(document).ready(function () {
$(".tagsinput").change(function (e) {
var value = $(this).val().replace(" ", "");
var words = value.split(",");
if (words.length > '#Model.TagsAllowed') {
alert("You are not allowed more than '#Model.TagsAllowed' tags!");
var lastword = value.split(",").pop();
value = value.replace(',' + lastword, '');
$(this).val(value);
$('.tagsinput').val() = value.substring(0, value.length - lastword.length);
}
});
})
Hope this helps anyone else somewhere along the line.

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>');
});
});

How to remove extra commas from a list

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.

Case insensitive jQuery attribute selector

I am doing the following using attribute contains selector $('[attribute*=value]')
<input name="man-news">
<input name="milkMan">
<script>
$( "input[name*='man']").css("background-color:black");
</script>
This works for the 1st input but not the second input as "Man" has a capital "M"
How can I make $( "input[name*='man']") an case insensitive selector?
The simplest way to do this is to add a case insensitivity flag 'i' inside the regex part of the selector:
So instead of
$( "input[name*='man']")
You could do
$( "input[name*='man' i]")
JS fiddle: https://jsfiddle.net/uoxvwxd1/3/
You can always use .filter():
var mans = $('input').filter(function() {
return $(this).attr('name').toLowerCase().indexOf('man') > -1;
});
mans.css('background-color', 'black');
The key part here is toLowerCase() which lowercases the name attribute, allowing you to test it for containing man.
var control = $('input').filter(function() {
return /*REGEX_VALUE*/i.test($(this).attr('id'));
});
*REGEX_VALUE* - the value you want to find
I ended up using regex to validate whether the attribute 'ID' satisfy... regex is much more flexible if you want to find a certain matching value or values, case sensitive or insensitive or a certain range of values...
I was just able to ignore jQuery's case sensitivity altogether to achieve what I want using below code,
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
You can use this link to find code based on your jQuery versions,
https://css-tricks.com/snippets/jquery/make-jquery-contains-case-insensitive/
Also there is an article where it does to many good things with jQuery: http://www.ultechspot.com/jquery/using-jquery-search-html-text-and-show-or-hide-accordingly
This works for me using jQuery and if i'm adding item to a table
// check if item already exists in table
var inputValue = $('#input').val(); // input
var checkitem = $('#exampleTable td.value div.editable').filter(function() {
//check each table's editable div matches the input value in lowercase
if ($(this).text().toLowerCase() === inputValue.toLowerCase()) {
itemexists = true;
}
});
if (itemexists) {
alert("item exists in the table");
return;
}

Categories

Resources