Remove a specific word from a div in jquery - javascript

checked input
<input id="add_stop" name="attach_img" type="checkbox" class="required custom-control-input">
Here is my div
<div class="emojionearea-editor">
Hello World. STOP to opt out
</div>
I want to remove just STOP to opt out if it exists in the inner HTML of div.
here is my jquery code
$('#add_stop').change(function (event) {
if ($(this).is(':checked')) {
if ($('.emojionearea-editor').html().indexOf("STOP to opt out") != -1) {
} else {
$('.emojionearea-editor').append('STOP to opt out ');
}
} else {
var name = $('.emojionearea-editor').html();
/* remove code should be here.... */
alert(name);
}
});
Here I want to add when checked. I append the text when it not exist. Now I want to remove text if it exists. Now my question is How can I remove the existing text from inner Html??

Is this what you are looking for?
$('#add_stop').change(function (event) {
var keyword = 'STOP to opt out';
if ($(this).is(':checked')) {
if ($('.emojionearea-editor').html().indexOf(keyword) != -1) {
} else {
$('.emojionearea-editor').append(keyword);
}
} else {
var name = $('.emojionearea-editor').text().replace(keyword,"");
alert(name);
}
});
I've made the words you want to replace into a variable. That way when you chance the text in the variable it will apply to every place where it's used.
Please note that you should use .text() and not .html() since the .html() will include all html code in that object.
Demo
$('#add_stop').change(function (event) {
var keyword = 'STOP to opt out';
if ($(this).is(':checked')) {
if ($('.emojionearea-editor').html().indexOf(keyword) != -1) {
} else {
$('.emojionearea-editor').append(keyword);
}
} else {
var name = $('.emojionearea-editor').text().replace(keyword,"");
alert(name);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="add_stop" name="attach_img" type="checkbox" class="required custom-control-input">
<div class="emojionearea-editor">
Hello World. STOP to opt out
</div>

html() function takes one parameter to set inner Html of the DOM.
So like this:
var text = $('.emojionearea-editor').html();
text = text.replace("STOP to opt out", "");
$('.emojionearea-editor').html(text);

var name = $('.emojionearea-editor').html().replace("STOP to opt out", "");
$('.emojionearea-editor').html(name)

I changed your JQuery code a bit
$("#add_stop").change(function() {
if(this.checked){
if(!$(".emojionearea-editor").html().includes("STOP to opt out ")){
$(".emojionearea-editor").append("STOP to opt out ")
}
}else{
var name = $('.emojionearea-editor').text();
$('.emojionearea-editor').text(name.replace("STOP to opt out ", ""))
alert(name);
}
})
This should allow you to add and remove the "STOP to opt out"
Here's a codepen with it working

Related

prevent users from entering duplicate entries in text inputs in javascript

I have a DOM in which I want to prevent users from entering duplicate entries in html text input.
The above DOM is not in user's control. It is coming through php.
At this moment, I am focussing only on name="code[]".
This is what I have tried:
$(function(){
$('input[name^="code"]').change(function() {
var $current = $(this);
$('input[name^="code"]').each(function() {
if ($(this).val() == $current.val())
{
alert('Duplicate code Found!');
}
});
});
});
Problem Statement:
I am wondering what changes I should make in javascript code above so that when a duplicate code is entered, alert message "Duplicate code Found" should come up.
you need to add an eventlistener to each item, not an eventlistener for all. Then count inputs with same value, if there's more than 1, it's a duplicate.
Also ignore not-filled inputs.
Check following snippet:
$('input[name*="code"]').each(function() {
$(this).change(function(){
let value = $(this).val();
let count = 0;
$('input[name*="code"]').each(function() {
if ($(this).val() != '' && $(this).val() == value) {
count++;
if (count > 1) alert('duplicate');
}
});
});
$(this).addClass('e');
});
$('#createInput').on('click', function(){
let newInput = document.createElement("input");
newInput.name = 'code[]';
newInput.type = 'text';
newInput.className = 'whatever';
$('#inputGroup').append(newInput);
// repeat the eventlistener again:
$('input[name*="code"]:not(.e').each(function() {
$(this).change(function(){
let value = $(this).val();
let count = 0;
$('input[name*="code"]').each(function() {
if ($(this).val() != '' && $(this).val() == value) {
count++;
if (count > 1) alert('duplicate');
}
});
});
$(this).addClass('e');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="inputGroup">
<input name="code-1" type="text" class="whatever">
<input name="code-2" type="text" class="whatever2">
<input name="code-3" type="text" class="whatever3">
</div>
<input type="button" id="createInput" value="Add input">
Edit:
now works with dynamically created elements. The class 'e' works as flag to not insert 2 event listeners to the same node element, otherwise they will run in cascade, provoking unwanted behaviour.
You can use something like this, that converts the jQuery object to an Array to map the values and find duplicates. I added an option to add a style to the duplicated inputs, so the user knows which ones are duplicated.
function checkDuplicates(){
var codes = $('input[name^="code"]').toArray().map(function(element){
return element.value;
})
var duplicates = codes.some(function(element, index, self){
return element && codes.indexOf(element) !== index;
});
return duplicates;
}
function flagDuplicates(){
var inputs = $('input[name^="code"]').toArray();
var codes = inputs.map(function(element){
return element.value;
});
var duplicates = 0;
codes.forEach(function(element, index){
var duplicate = element && codes.indexOf(element) !== index;
if(duplicate){
inputs[index].style.backgroundColor = "red";
inputs[codes.indexOf(element)].style.backgroundColor = "red";
duplicates++
}
});
return duplicates;
}
$('input[name^="code"]').on("change", function(){
//var duplicates = checkDuplicates(); // use this if you only need to show if there are duplicates, but not highlight which ones
var duplicates = flagDuplicates(); // use this to flag duplicates
if(duplicates){
alert(duplicates+" duplicate code(s)");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="code-1" type="text">
<input name="code-2" type="text">
<input name="code-3" type="text">

How to stop an event happening in Javascript

On this simple to-do list how do i stop the program from still creating a new paragraph when there is nothing in the text field. When Add To List is blank, i want the function to only output the alert, nothing else. I've tried many things but nothing has worked. Any help is greatly appreciated. Thanks!
JS Fiddle = http://jsfiddle.net/Renay/g79ssyqv/20/
<p id="addTask"> <b><u> To-Do List </u> </b> </p>
<input type='text' id='inputTask'/>
<input type='button' onclick='addText()' value='Add To List'/>
function addText(){
var input = document.getElementById('inputTask').value;
var node=document.createElement("p");
var textnode=document.createTextNode(input)
node.appendChild(textnode);
document.getElementById('addTask').appendChild(node);
var removeTask = document.createElement('input');
removeTask.setAttribute('type', 'button');
removeTask.setAttribute("value", "Remove");
removeTask.setAttribute("id", "removeButton");
removeTask.addEventListener('click', function() {
node.parentNode.removeChild(node);
}, false)
node.appendChild(removeTask);
if (input == "") {
alert('Please add an entry');
}
}
Move your if statement to the top, just after your input variable is assigned to, and add a return to it to break out of the function:
function addText() {
var input = ...;
if (input == "") {
alert("...");
return;
}
var node ...;
...
}
Amended JSFiddle demo.
When a return statement is called in a function, the execution of this function is stopped. If specified, a given value is returned to the function caller. If the expression is omitted, undefined is returned instead. (MDN)
You could just move the "creation" section in your else block
var input = document.getElementById('inputTask').value;
if (input == "") {
alert('Please add an entry');
} else {
var node=document.createElement("p");
var textnode=document.createTextNode(input)
node.appendChild(textnode);
document.getElementById('addTask').appendChild(node);
var removeTask = document.createElement('input');
removeTask.setAttribute('type', 'button');
removeTask.setAttribute("value", "Remove");
removeTask.setAttribute("id", "removeButton");
removeTask.addEventListener('click', function() {
node.parentNode.removeChild(node);
}, false)
node.appendChild(removeTask);
}

I want to disable the button if specific text has been found in any label

I want to disable the button if specific text has been found in any label.
The following code doesn't run because aTags[i].innerText is not equal to searchText all the time which is wrong because the label has inner text = "a" and the searchText variable have "a" as text - I need it to run in IE
<html>
<script language="javascript">
$(document).ready(function () {
var aTags = document.getElementsByTagName("label");
var searchText = "a";
var found;
for (var i = 0; i < aTags.length; i++) {
if (aTags[i].innerText == searchText) {
document.getElementById('choose').disabled=true;
break;
}
else
{
alert("failed")
}
}
});
</script>
<label> a </label> <br/>
<label> b </label> <br/>
<label> c </label> <br/>
<input type='button' value='choose' id='choose' />
</html>
Seems like there should be easier ways to do that with jQuery
$(function () {
var searchText = "a";
$('#choose').prop('disabled', function() {
return $('label').filter(function(_,el) {
return $.trim( $(el).text() ) === searchText;
}).length > 0;
});
});
FIDDLE
The issue is that your label contains " a " (with the spaces), but you're comparing with "a" (no spaces).
If you want to ignore the spaces, you can use jQuery's $.trim(...) to trim the text off the innerText.
But as you're using jQuery, you can dramatically reduce that code:
$(document).ready(function() {
var searchText = "a";
var found = false;
$("label").each(function() {
found = $.trim($(this).text()) === searchText;
if (found) {
return false; // No need to keep looking
}
});
$("#choose").prop("disabled", true);
});
Since you're already using jQuery, you can do what you like with much less complexity.
This will work:
(function ($) {
var searchText = "a";
$('label').each(function(){
if ($.trim($(this).text()) === searchText) {
$('#choose').prop('disabled', true);
}
});
})(jQuery);
You have to trim label's text. Try with:
if (aTags[i].innerText.trim() == searchText)
or without trim method:
if (aTags[i].innerText.replace(/^\s+|\s+$/g, '') == searchText)
If you want to match if a substring exists you can try with
aTags[i].innerText.indexOf(searchText) > -1
instead of
aTags[i].innerText == searchText

How to hide the parent of an unchecked checkbox?

I have a set of random/dynamic generated div checkboxes:
<div>A1 <input type='checkbox' name='A[]' value='A1'> </div>
<div>A2 <input type='checkbox' name='A[]' value='A2'> </div>
<div>A3 <input type='checkbox' name='A[]' value='A3'> </div>
<div>B1 <input type='checkbox' name='B[]' value='B1'> </div>
<div>B2 <input type='checkbox' name='B[]' value='B2'> </div>
<div>C1 <input type='checkbox' name='C[]' value='C1'> </div>
What I am trying to do is when the user:
checks any A then the others will hide (entire div) but all A will still show.
unchecks a checkbox, then all A, B, C will show again.
This is because I am preventing the user from checking a mix of options.
PS:
You can provide a solution that might need me to modify the generated output of checkboxes.
try this fiddle
$("input[type=checkbox]").on("change", function() {
var thisName = $(this).attr("name");
if($(this).is(':checked')){
$(':checkbox').parent().hide();
$('input:checkbox[name|="'+thisName+'"]').parent().show();
} else {
$(':checkbox').parent().show();
}
});​
Try this one,
$('input:checkbox').click(function(){
if($(this).attr('checked') == 'checked'){
$('input:checkbox').parent('div').hide();
$('input:checkbox[name="'+$(this).attr('name')+'"]').parent('div').show();
}else{
if(!$('input:checkbox[checked="checked"]').length){
$('input:checkbox').parent('div').show();
}
}
})
​
Demo: http://jsfiddle.net/muthkum/uRd3e/3/
You can use some JQuery traversing to hide the non-matching elements:
// add the event handler
$("input[type=checkbox]").on("change", function() {
// get whether checked or unchecked
var checked = $(this).prop("checked") === true;
// get the name of the clicked element (eg, "A[]")
var thisName = $(this).prop("name");
// get the name of the clicked element (eg, "A[]")
var thisName = $(this).prop("name");
// get the grandparent element
$(this).parent().parent()
// get all the checkboxes
.find("input[type=checkbox]")
// filter to only the ones that don't match the current name
.filter(function(i, e) { return e.name != thisName; })
// hide or display them
.css("display", checked ? "none" : "");
});
you can simple do it like this
$('input[type=checkbox]').change(function () {
if ($(this).attr('checked')) {
var Name = $(this).prop("name");
$('div').filter(function(){
return $(this).find('input[type=checkbox]').prop("name") != Name;
}).hide();
}
else
{
$('input[type=checkbox]').attr('checked',false);
$('input[type=checkbox]').parent('div').show();
}
});​
Live Demo
Try code bellow:
$(":checkbox").click(function() {
var identifier = $(this).val().substring(0, 1);
$("input[type='checkbox']").each(function() {
if ($(this).val().indexOf(identifier) != -1) {
$(this).parent().show();
} else {
$(this).parent().hide();
}
});
if ($("input:checked").length == 0) {
$("input[type='checkbox']").parent().show();
}
});
You can try on jsFiddle
This will hide all other checkbox types when FIRST of a type is checked and show all the other checkbox types when ALL of the checked box type are unchecked:
$("input:checkbox").on("change", function() {
// get the name attribute
var nameAttr = $(this).prop("name");
// check how many checkbox inputs of that name attribute are checked
var checkedLength = $("input:checkbox[name=\"" + nameAttr + "\"]:checked").length;
// if 0, display other checkbox inputs, else if 1 hide all of the rest
if(checkedLength == 0) {
$("input:checkbox[name!=\"" + nameAttr + "\"]").parent().show();
}else if(checkedLength == 1) {
$("input:checkbox[name!=\"" + nameAttr + "\"]").parent().hide();
}
});
Overwhelmed by choice! Here's a plain JS version that just disables members of the non–selected groups.
I think that's better than hiding them so users can see the other options after they've selected one. Otherwise, to see the other options again, they must deselect all checkboxes in the group.
Note that div is a parent of the inputs, the listener passes a reference to the element and the related event object, modify as required.
<script>
function doStuff(div, evt) {
var checked, el, group, j, inputs, name, re;
var t = evt.target || evt.srcElement;
if (t.nodeName && t.nodeName.toLowerCase() == 'input' && t.type == 'checkbox') {
inputs = div.getElementsByTagName('input');
name = t.name;
// Set checked to true if any input with this name is checked
group = document.getElementsByName(name);
j = group.length;
while (j-- && !checked) {
checked = group[j].checked;
}
// Loop over inputs, hide or show depending on tests
for (var i=0, iLen=inputs.length; i<iLen; i++) {
el = inputs[i];
// If name doesn't match, disable
el.disabled = checked? (el.name != name) : false;
}
}
}
</script>
<div onclick="doStuff(this, event)">
<div>A1 <input type='checkbox' name='A[]' value='A1'></div>
<div>A2 <input type='checkbox' name='A[]' value='A2'></div>
<div>A3 <input type='checkbox' name='A[]' value='A3'></div>
<div>B1 <input type='checkbox' name='B[]' value='B1'></div>
<div>B2 <input type='checkbox' name='B[]' value='B2'></div>
<div>C1 <input type='checkbox' name='C[]' value='C1'></div>
</div>
Thanks guys, especially dbaseman (get me ideal) :
ok, Here is my code after referring from you all.
$("input[type=checkbox]").on("click", function() {
var sta = $(this).is(":checked"); sta=(sta==true?1:0);
if(sta==1){
var thisName = $(this).prop("name"); thisName=thisName.replace("[]","");
$("div input[type=checkbox]:not([name^=" + thisName + "])").parent().hide();
}else{
var num = $("[type=checkbox]:checked").length;
if(num==0){
$("div input[type=checkbox]").parent().show();
}
}
});
so far code able is performing as what i need.
Ps: i am still weak on jquery travelling part
Ps: Edited on re-opening all checkboxes part
Thanks once again!

If input box contains certain number of characters

<input type="text"/> <button>Go</button>
<div id="example">
</div>
How can I .append "Blah" in #example if input contains 5 characters when button is clicked, and .append "Other" if it doesn't?
var example = $('#example'); //get example div
var input = $('input').get(0); //get first input in the set of inputs
$('button').click(function(){ //bind click handlers to (any) button
var value = input.value; //get the (first) input's value
if(value.length === 5){ //check the value
example.append('Blah');
} else {
example.append('Other');
}
});
$('button').click(function() {
var $example = $('#example');
if ($('input').val().length == 5) {
$example.append('Blah');
} else {
$example.append('Other');
}
});
http://jsfiddle.net/zerkms/cks45/
$(function(){
$('button').click(function(){
if($('input').val().length == 5){
$('#example').append('blah');
}else{
$('#example').append('Other');
}
});
});
Pure JS way
var butt = document.getElementsByTagName("button")[0],
input = document.getElementsByTagName("input")[0],
example = document.getElementById("example");
butt.onclick = function(){
if(input.value.length == 5){
example.textContent += "blah";
}else{
example.textContent += "other";
}
}
​
Live Demo
​
$('button').on('click',function() {
$('#example').text(
$('#example').text() +
($('input[type=text]').val().length==5?'Blah':'Other')
);
} );
If you didn't want to use jquery you could do...
HTML
<input id="input1" type="text"/> <button onclick="go('input1')">Go</button>
<div id="example">
</div>
JavaScript
function go(inputId){
document.getElementById("example").innerHTML += document.getElementById(inputId).value.length === 5 ? "bla" : "other";
}
This involved changing the HTML to include an id for the input and an onclick event handler for the button.

Categories

Resources