<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.
Related
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
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">
So basically I have a button .button, which adds a number to my input #number everytime it's pressed.
Now, when I already have 7 digits in my input #number, I want the function to like 'stop working'.
Here is my code (works fine):
function nrtwo(hello){
var das = $(hello).html();
var tempNum = $("#number").val();
$("#number").val(tempNum + '' + das);
tempNum = null;
};
$(".button").click(function(){
nrtwo(this);
});
I was thinking of something like this?
if ($("#number").attr('maxlength') == '7') {
return false;
}
Thanks for the help.
Try this .length it is a Number and unblind click event when you reach 7 digits :
Working jsFiddle
$(".button").click(function(){
if ($("#number").val().length == 7) {
$(this).unbind('click');
return false;
}else{
nrtwo(this);
}
});
You need to handle this scenario in the click event itself. Please see the following example:
$(".button").click(function(){
if ($("#number").val().length <= 7) {
nrtwo(this);
}
});
This will only call the nrtwo method only when the input's length is less than or equals to 7.
If you are handling numbers only, you can also check the numeric value before adding to it.
$('#add').click(function() {
var value = parseInt($('#output').val());
if(value <= 999999) {
$('#output').val(value + 1);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add">Add</button>
<input type="text" id="output" value="999995" />
$('#number').keypress(function(event){
var n = $(this).val();
if(n.length == 7){
event.preventDefault(); //stop character from entering input
}
if(event.which != 8 && isNaN(String.fromCharCode(event.which))){
event.preventDefault(); //stop character from entering input
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<input id="number"/>
One method is to use .length property.
Please try this:
if ($("#number").val().length == '7') {
return false;
}
$('#add').click(function() {
if ($("input").val().length != '7') {
$('input').val(parseInt($('input').val())+1);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" value="999998"/>
<button type="button" id="add">Add</button>
I am trying to find the empty input types like textbox, select and li elements inside a jQuery resultset.
My resultset is (requiredfields) -
$requiredFields = $(".f-form-required.f-form-field").filter(function(){
if($(':input:not([type="hidden"])'))
return $(this);
});
And on that resultset I want to query for empty inputs like textbox, select and li elements. But it seems I am doing something wrong. Can someone suggest me how to do that.
Currently I am doing this to get empty textboxes but not working -
var emptyInputs = 0;
$requiredFields.filter(function(){
$('input[type=text]').each(function(){
if (this.val == "") {
emptyInputs = emptyInputs + 1;
}
});
});
I am trying to do same for finding out empty dropdown/select elements and list / li elements over $requiredFields collection.
There is no val property. Try using .val() instead or this.value:
var emptyInputs = 0;
$requiredFields.filter(function(){
$('input[type=text]').each(function(){
if (jQuery(this).val() == "") {
emptyInputs = emptyInputs + 1;
}
});
});
or:
var emptyInputs = 0;
$requiredFields.filter(function(){
$('input[type=text]').each(function(){
if (this.value == "") {
emptyInputs = emptyInputs + 1;
}
});
});
I think you arn't using .filter() quite as it is expected to be used. Consider something like this:
<html>
<body>
<div>
<input type="text" id="text1" class="f-form-required f-form-field" />
<input type="text" id="text2" class="f-form-required f-form-field" value="test" />
<input type="text" id="text3" class="f-form-required f-form-field" />
</div>
</body>
</html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function test(){
var $requiredFields = $('.f-form-required.f-form-field');
var $errorFields = $requiredFields.filter(function () {
var $this = $(this);
return $this.is('input') && $this.val() === '';
});
var errorCount = $errorFields.length;
console.log('errors:' + errorCount);
}
$(document).ready(function(){
test();
}
</script>
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!