Trigger change or input when javascript changes input value - javascript

I'm working in a little project with JQuery, and i having a problem removing error classes from html elements.
I'm using $('selector').on('input') to get the event and remove the input class, my problem is when the field is generated with JavaScript;
Example
$('#one').on('input',function(){
$('#two').val( $('#one').val() );
});
$(':input').on('input', function ()
{
if ($(this).hasClass('example'))
{
$(this).removeClass('example');
}
});
.example
{
color: orange;
background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Normal Case</h2>
<input type="text" class="example">
<h2>Problem</h2>
<label for="one">#ONE</label>
<input type="text" class="example" id="one">
<br/>
<label for="two">#TWO</label>
<input type="text" class="example" readonly="readonly" id="two">
In this case, i change #two value when #one changes, #one remove .example but #two dont
I need to remove .example class from #two input
EDIT: I want to do it in a generic way because i have a LOT of this cases in my project
Is some way to trigger that kind of changes?
Thanks so much!

Maybe the code I wrote below help you. It's not perfect but it's a good point of start.
I added a custom attribute that I called data-group for the inputs that are of the same "group".
I also modified the listener for input in a way that from a single listener function, you will have all inputs listening.
Check if this helps you.
$('.example').on('input',function(){
var value = this.value;
var groupName = $(this).attr('data-group');
var groupElems = $("[data-group='"+groupName+"']");
groupElems.removeClass('example');
groupElems.val(value);
});
.example
{
color: orange;
background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Problem</h2>
<label for="one">#ONE</label>
<input type="text" class="example" data-group="group1" id="one">
<br/>
<label for="two">#TWO</label>
<input type="text" class="example" data-group="group1" readonly="readonly" id="two">
<h2>Problem</h2>
<label for="three">#THREE</label>
<input type="text" class="example" data-group="group2" id="three">
<br/>
<label for="four">#FOUR</label>
<input type="text" class="example" data-group="group2" readonly="readonly" id="four">
<h2>Problem</h2>
<label for="five">#FIVE</label>
<input type="text" class="example" data-group="group3" id="five">
<br/>
<label for="six">#SIX</label>
<input type="text" class="example" data-group="group3" readonly="readonly" id="six">

Inside the true branch of your if statement, use the .nextAll() method, along with a selector to find the next input following this. That way, when the first input has the class removed, the next input that follows it will have its class removed as well.
Also, change your input event setup so that it is set to work on input elements of a certain class in the first place and give the first of each set of inputs that class.
$('#one').on('input',function(){
$('#two').val( $('#one').val() );
});
// Only when an input with the "input" class gets input
$('input.input').on('input', function () {
if ($(this).hasClass('input')) {
$(this).removeClass('input');
// Find the next input sibling that follows "this"
$(this).nextAll("input").removeClass("input");
}
});
.input {
color: orange;
background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Normal Case</h2>
<input type="text" class="input">
<h2>Problem</h2>
<label for="one">#ONE</label>
<input type="text" class="input" id="one">
<br>
<label for="two">#TWO</label>
<input type="text" class="input" readonly="readonly" id="two">

You can check, if the current field is #one using .is() :
$(':input').on('input', function () {
if(($(this).is("#one"))) {
if ($('#two').hasClass('example'))
{
$('#two').removeClass('example');
}
}
if ($(this).hasClass('example'))
{
$(this).removeClass('example');
}
});

Related

not hiding dropdown when focus changes

Let's imagine I have three inputs :
<input type="text" id="a">
<input type="text" id="b">
<input type="text" id="c">
and one div table that should drop down when writing some data into input "a" or input "b".
Well the logic I want to to take is:{
if you click and add some data to input a show that table to me->table appears->if I click on input b dont hide that div, however if I click somewhere else for example in input c, hide the table.
It's been 3rd day I cannot do this.
P.S. My boss told not to use $timeout. It should be done with blur and focus
Just wrap input a and b in same class and then use blur and focus on that class.
$(document).ready(function(){
$('#showab').hide();
$("input.change").focus(function(){
$('#showab').show();
});
$("input.change").blur(function(){
$('#showab').hide();
});
});
input{
display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="change" type="text" id="a">
<input class="change" type="text" id="b">
<input type="text" id="c">
<div id="showab">table here</div>
$("#showData").hide();
function lookup(arg) {
var id = arg.getAttribute('id');
var value = this.value;
console.log(id);
if (id === "a" || id === "b") {
$("#showData").show();
} else {
$("#showData").hide();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="a" onkeyup="lookup(this);" onClick="lookup(this);">
<input type="text" id="b" onkeyup="lookup(this);" onClick="lookup(this);">
<input type="text" id="c" onkeyup="lookup(this);" onClick="lookup(this);">
<div id="showData">A Or B is Clicked here</div>
You want to make use of classes when hiding or showing your div containing the table.
Also take note of the Jquery focus (click into) and blur (click out of) classes
$(".show").focus(function()
{
$('#showTable').show();
});
$(".show").blur(function()
{
$('#showTable').hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="show" type="text" id="a">
<input class="show" type="text" id="b">
<input class="dontShow" type="text" id="c">
<div id="showTable" hidden="hidden">
<table>
<thead>
<tr><th>test 1</th><th>test 2</th></tr>
</thead>
<tbody>
<tr><td>1</td><td>2</td></tr>
<tr><td>3</td><td>4</td></tr>
</tbody>
</table>
</div>

How to append HTML content using Jquery

All what I want to do is, when the user clicks on a button, the content of the div should append at the bottom. My code works fine if I paste the content inside the div in the javascript displayed below:
My question:
1.) Without having to copy paste the code that was in the HTML to JAVASCRIPT is there any other way I could get this done.
2.) I want the name and also the value attribute of the input field to be unique (like append a number at the end ). How can I do this ?
My jQuery looks like this:
$(document).ready(function(){
$("#btn").click(function(){
$("#boxid").append('<br/>
<div class="input-group">
<input type="text" class="form-control" id="myid" placeholder="hey" value="2">
<div class="input-group-addon">?</div>
</div>
');
});
});
HTML
<button id="btn">Add another row</button>
<form action="gone/" method="get">
<div id="boxid">
<div class="input-group">
<input type="text" class="form-control" id="myid" placeholder="hey" value="2">
<div class="input-group-addon">?</div>
</div>
</div>
</form>
You can use $.clone().
$(document).ready(function() {
var counter = $('.form-control').last().val();//Get the last .form-control value, in case you decide to have more than one by default (this way the counter can start from 2 e.g)
$("#btn").click(function() {
counter++; //Increase counter
$("#boxid").append($('.input-group').eq(0).clone()); //Clone the existing first .input-group
$("#boxid .input-group").last().find('.form-control').attr('name', counter).val(counter); //Select the last appended .input-group, find the .form-control input, change input's name and value with the counter
});
});
.input-group{
margin-bottom: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">Add another row</button>
<form action="gone/" method="get">
<div id="boxid">
<div class="input-group">
<input type="text" class="form-control" id="myid" placeholder="hey" value="1" name="1">
<div class="input-group-addon">?</div>
</div>
</div>
</form>
Initialize counter with the last input's value
In case of click on #btn increase counter.
Append to #boxid the clone of the first (.eq(0)) .input-group (It doesn't really matter if it's the first, just used it as first = template).
Select the last .input-group inside #boxid and change its name and value with the counter.
I left your <br>behind, is not used nowadays, a more correct way is using css margin (a margin of 1em is like 1 text line)
Try this code :
$(document).ready(function(){
$("#btn").click(function(){
if(checkUnique('myid')){//to check unique id
$("#boxid").append('<br/>
<div class="input-group">
<input type="text" class="form-control" id="myid" placeholder="hey" value="2">
<div class="input-group-addon">?</div>
</div>
');
}
else{
$("#boxid").append('<br/>
<div class="input-group">
<input type="text" class="form-control" id="myid1" placeholder="hey" value="2">
<div class="input-group-addon">?</div>
</div>
');
}
});
});
function checkUnique(ex){
if($('#'+ex).length==0){
return true;}
else
{return false;}
}
When i need something like this is, i use a hidden div containing template elements. When ever i need a realization of a template, i simply copy the template, change some placeholders and add it to my target element.
PS: include https://jsfiddle.net/cvf2f7dn/1/ of #Illep
css
#templates { display: none }
html
<div id="targetDiv"></div>
<div id="templates">
<div id="templeateForInputGroup">
<div class="input-group">
<input type="text" class="form-control" id="myid%%counter%%" placeholder="hey" value="%%counter%%">
<div class="input-group-addon">?</div>
</div>
</div>
</div>
<button id="addmore">Add more</button>
js
$('#addmore').click(add);
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};
var counter = 0;
function add(){
var cloneHTML = $('#templeateForInputGroup').html().toString();
cloneHTML = cloneHTML.replaceAll('%%counter%%', counter);
counter++;
$('#targetDiv').append(cloneHTML);
}

Mark label as red when required input is not filled

Lets say I have this form input element:
<label for="myInput">Label Text</label>
<input type="text" name="special" id="myInput" required>
Now since this input is required, and I don't enter any values in this field, I get an error saying
This field is required.
Validation: It appears that the existing default html5 validation is overridden by jQuery validator. There is magic happening, and I see that I can change the existing style behavior by changing the below css
select.error,
input[type=text].error,
input[type=email].error,
input[type=password].error {
border: 2px solid #ff0000;
}
label.error {
color: #ff0000;
font-size: .8em;
}
I also notice that in the error situation the above html becomes like below:
<label for="myInput">Label Text</label>
<input type="text" name="special" id="myInput" required>
<label class="error" for="myInput">This field is required.</label>
How do you think validation is happening in the first place?
How do I make the text in the first label element text as red?
In the code, where should I be looking to answer the above questions?
first use id attribute for label
<label for="myInput" id="mylabel">Label Text</label>
, then document.getElementById('mylabel').style.color = "red";
you can write this code on some button click or onblur of text box
DEMO
If you are using jquery then you can refer the below code
$( "#myInput" ).blur(function() {
document.getElementById('mylabel').style.color = "red";
});
JS solution
html
<label for="myInput" id="mylabel">Label Text</label>
<input type="text" name="special" onblur="blurFunction()" onfocus="focusFunction()" id="myInput">
js
function blurFunction()
{
document.getElementById('mylabel').style.color = "red";
}

How to toggle div visibility using radio buttons?

I'm working on a project in which I have to toggle the visibility of a <div>.
I've got the following code:
<input type="radio" name="type" value="1"> Personal
<input type="radio" name="type" value="2"> Business
<div class="business-fields">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>
I would like to togle the business-fields div. So, if none of the radio buttons, or the 'personal' radio button is selected: The div should be hidden. If the 'business' radio button is selected, I want it to show.
Currently, I am using this code:
$("input[name='type']").click(function() {
var status = $(this).val();
if (status == 2) {
$(".business-fields").show();
} else {
$(".business-fields").hide();
}
});
However, I was wondering if I can do this using the .toggle() function.
I usually tend not to use JS if possible, therefore here comes a HTML+CSS way approach.
.bussines-type .business-fields {
display: none;
}
.bussines-type input[value="2"]:checked ~ .business-fields {
display: block;
}
<div class="bussines-type">
<input id="bt1" type="radio" name="type" value="1">
<label for="bt1"> Personal</label>
<input id="bt2" type="radio" name="type" value="2">
<label for="bt2"> Business</label>
<div class="business-fields">
<input type="text" placeholder="Company name" name="company-name">
<input type="text" placeholder="Vat number" name="vat-number">
</div>
</div>
The ~ stands for any siblings, that are after the element we defined before the ~ sign.
I'd suggest using the change event, and supplying a Boolean switch to the toggle() method, which will show the jQuery collection of elements if the switch evaluates to true, and hide them if it evaluates to false:
// select the relevant <input> elements, and using on() to bind a change event-handler:
$('input[name="type"]').on('change', function() {
// this, in the anonymous function, refers to the changed-<input>:
// select the element(s) you want to show/hide:
$('.business-fields')
// pass a Boolean to the method, if the numeric-value of the changed-<input>
// is exactly equal to 2 and that <input> is checked, the .business-fields
// will be shown:
.toggle(+this.value === 2 && this.checked);
// trigger the change event, to show/hide the .business-fields element(s) on
// page-load:
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type="radio" name="type" value="1">Personal</label>
<label>
<input type="radio" name="type" value="2">Business</label>
<div class="business-fields">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>
Incidentally, note I've also wrapped the associated text, to indicate the radio-button's purpose, inside of a <label> element to directly associate that text with the <input>, so clicking the text checks the <input> automatically.
References:
change().
on().
toggle().
JS Fiddle
Try this one
<input type="radio" name="type" value="1" checked ="true"> Personal
<input type="radio" name="type" value="2"> Business
<div class="business-fields">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>
.business-fields{
display: none;
}
$("input[name='type']").change(function() {
$(".business-fields").toggle();
});
You may use like this:
$("input[name='type']").change(function() {
var status = $(this).val();
if (status != 2) {
$(".business-fields").hide();
} else {
$(".business-fields").show();
}
});
.show and .hide are pretty slow.
https://twitter.com/paul_irish/status/564443848613847040
It's better to toggle a css class on and off with javascript. Set the css of the class to {visibility: hidden} or {display: none}
use the below code
<script>
$(function(){
$(":radio[value=1]").click(function(){
var isVisible = $( ".business-fields" ).is( ":visible" );
if(isVisible==true)
$('.business-fields').toggle();
});
$(":radio[value=2]").click(function(){
var isVisible = $( ".business-fields" ).is( ":visible" );
if(isVisible==false)
$('.business-fields').toggle();
});
});
</script>
AND HTML is-
<input name="type" type="radio" value="1" >Personal
<input type="radio" name="type" value="2" checked="checked"> Business
<div class="business-fields">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>
Possibly a more elegant solution, It's a bit more readable in my opinion, and and as #Ollie_W points out it might be more performant that toggle (show/hide).
$('input[name="type"]').on('change', function(event) {
var radioButton = $(event.currentTarget),
isBusiness = radioButton.val() === 'business' && radioButton.prop('checked');
$('.business-fields').toggleClass('hidden', !isBusiness);
}).change();
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type="radio" name="type" value="personal">Personal</label>
<label>
<input type="radio" name="type" value="business">Business</label>
<div class="business-fields hidden">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>

Bind two inputs so they display the same text even if one of them was changed by user

The jQuery code looks like this and works fine (probably it look a bit sorter, so please let me know and I'll change it either): jsFiddle
jQuery:
$('.inputs').on('keyup',function(){
$(this).parent().not(this).find('.inputs').val($(this).val());
}
);
HTML:
<div>
<input type="text" class="inputs" value="hello">
<input type="text" class="inputs" value="John">
</div>
How can I rewrite this code for knockout.js?
Thank you.
Take a look at the below code snippet which will work fine with ko.
var value = "Hello John";
var viewModel = {
Name: ko.observable(value)
};
ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.0.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" data-bind="value:Name" class="inputs" id="first">
<input type="text" data-bind="value:Name" class="inputs" id="second">
</div>
<span data-bind="text: Name"> </span>
Hope, You will do this with more data. In that case, Take a look at this sample which will let you know about how to support more data.
For more faqs visit jqfaq.com
Just bind it to the same observable:
HTML
<div>
<input type="text" class="inputs" id="first" data-bind="value:foobar,valueUpdate:'keyup'">
<input type="text" class="inputs" id="second" data-bind="value:foobar,valueUpdate:'keyup'">
</div>
ViewModel
function AppViewModel() {
this.foobar = ko.observable('hello');
}
ko.applyBindings(new AppViewModel());
I used the valueUpdate binding to update the inputs in real time instead of on blur (see also: https://stackoverflow.com/a/4391419/664108)

Categories

Resources