check inputfields on pageload and manipulate with jquery - javascript

When I press ADD, I show the hidden #box, I hide the ADD button and show the REMOVE button.
html:
<input type="button" id="add" value="ADD">
<input type="button" class="no-display" id="remove" value="REMOVE">
<div class="no-display" id="box">
<input id="a" value="" type="text" />
<input id="b" value="" type="text" />
<input id="c" value="" type="text" />
</div>
jquery:
$('#add,#remove').click(function () {
$('#add').toggle();
$('#remove').toggle();
$('#box').slideToggle("fast");
});
see working DEMO
Now, I want to check if the input fields #a or #b or #c have a value. If they have a value, on pageload I want to show #box, hide the #add button and show the #remove button.
What is the best way to do this?
you can see a DEMO here (not finished)

using filter() to get the count of the input that has value on it... if count is greater that 0 ..means atleast one input is not empty so.. hide add, show remove buttons and the container
try this
$('#add,#remove').click(function () {
$('#add').toggle();
$('#remove').toggle();
$('#box').slideToggle("fast");
});
var count = $('#a,#b,#c').filter(function () {
return $(this).val().length > 0;
}).length;
if (count > 0) {
$('#box').show();
$('#add').hide();
$('#remove').show();
}
updated as per comment
var count = $('#a,#b,#c').filter(function () {
return this.value.length > 0; //faster
}).length;
working fiddle

Try this: Move toggle code to a function. Bind it to the click. Call it on load if any of the inputs have a value.
$(function () {
var toggleBox = function () {
$('#add').toggle();
$('#remove').toggle();
$('#box').slideToggle("fast");
};
$('#add,#remove').click(toggleBox);
if(!!$("#a, #b, #c").filter(function() {return this.value;}).length) {
toggleBox();
}
});

Related

js active button when number of input is 10 characters

I want to make a disabled button changed into active button automatically using js when the number of input is 10 character in the input field.
<input type="text" class="form-control" name="client_phone1" placeholder="01**********">
<button type="submit" formaction="{{url('/client-mobile-login')}}" disabled class="mobile-login__button">CONTINUE
</button>
in this input field number of character is 10 then the submit button will active actomatically
what will be the js code?
first add event listener to the input, then check if the value is equal to 10 and disable the button.
<input type="text" name="Thing" id="Thing" value="" />
<button type="submit" formaction="{{url('/client-mobile-login')}}" id='mybtn' class="mobile-login__button">CONTINUE
</button>
window.onload = function() {
/* event listener */
document.getElementById("Thing").addEventListener('keyup', doThing);
/* function */
function doThing() {
console.log(this.value)
if (this.value.length === 10) {
document.getElementById("mybtn").disabled = true;
} else {
document.getElementById("mybtn").disabled = false;
}
}
}
Edit: Example on JSFiddle JSFiddle

Show element in JavaScript by onkeypress function

I'm trying to show save button only if input gets value,
The issue is if i use append for each input i get 1 button printed, what I'm looking for is regardless of input length get the button only once.
The important is input not be empty that's all.
Code
<input class="text_dec form-control" type="text" onkeypress="myFunction()" name="text_dec[]" id="'+ textFieldsCount.toString() +'">
function myFunction() {
$('#moreless').append("button here");
}
any idea?
Instead of keypress, use keyup, this will call the listener just when the key is released, so you will have the correct length of the input value. With that, you can check if the button must be displayed or not.
Also, I would have another check to make sure that input have some value on it to save when clicked.
Like below, take a look:
$(function(){
$('.myInput').on('keyup', function(){
var btnElem = $('.myButton');
var charLength = this.value.length;
if (charLength > 0){
btnElem.show();
}else {
btnElem.hide();
}
});
$(".myButton").on("click", function(){
if ($('.myInput').val().trim().length < 1){
alert("Input is empty")
return;
}
//Do your code
});
});
.myButton {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input class="myInput" type="text" value="">
<input class="myButton" type="button" value="Save Button" />
</body>
EDIT
Now, if you really need to make as you were doing before (I don't consider it a best practice and also recommend you to rethink if you really wanna go through this) here goes a code that will help you. Click to show.
Here I added the functions and created the button element (if necessary) then append it to DOM just when the input have some value length.
function myFunction(input){
var btnElem = $(".mySaveButton")[0];
if (!btnElem){
btnElem = document.createElement("button");
btnElem.textContent = "Save Button";
btnElem.onclick = btnClicked;
btnElem.className = "mySaveButton";
}
var charLength = input.value.length;
if (charLength > 0){
document.body.append(btnElem);
}else {
btnElem.remove();
}
};
function btnClicked(){
if ($('.myInput').val().trim().length < 1){
alert("Input is empty")
return;
}
//Do your code
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input class="myInput" type="text" value="" onkeyup="myFunction(this)">
</body>
So I think you just want a button to show to the user once they type something in the text box. If that's the case, then you don't really want to append a button every time they press a key in the box.
Instead I'd make a button and set its css to display none and then when they keydown in the text box change the button's css to display block.
Something like this: http://jsfiddle.net/wug1bmse/10/
<body>
<input type="text">
<input class="myButton" type="button" value="button text" />
</body>
.myButton {
display: none;
}
$(function(){
$('input').on('keypress',function(){
var htmlElement= $('.myButton');
htmlElement.css('display', 'block');
});
});
Hiding the element with a class might be easier:
.btn-hidden {
display: none;
}
<input id="save-button" class="btn-hidden" type="button" value="save" />
function showSave() {
$('#save-button').removeClass('btn-hidden');
}
function hideSave() {
$('#save-button').addClass('btn-hidden');
}

Increasing and decreasing value of the clicks of the button

Hi how can I make a button that will increase and decrease a value? I the button to add 1 when clicked once and reduced the value by 1 when clicked again so it can't count to more than 1.
I have around 50 buttons and currently, it resets when I choose more than 2 buttons, but it has to add all the values of the buttons that were clicked once. Site around it looks similar to this:
var clicks = 0;
function clickME() {
clicks += 1;
if (clicks == 2) {
clicks = 0;
}
document.getElementById("clicks").innerHTML = clicks;
}
<input type="Button" id="bt" />
Considering each button (or more generically each element) is part of the DOM (Document Object Model), each one is an object, so no one makes you unable to use them: you can set the field clicks for each button DOM object:
function clickME(event) {
var btn = event.target;
btn.clicks = ((btn.clicks || 0) + 1) % 2;
window.clicks = (window.clicks || 0) + btn.clicks * 2 - 1;
document.getElementById("clicks").innerText = window.clicks;
}
Checking out your code, I also simplified your logic replacing the if to check zero with the MOD (%) operator. Furthermore I replaced innerHTML with innerText because the number we won't to be rendered as HTML code, but as plain text, although in this case, it doesn't make difference.
Note:
Don't forget to pass the event data object with the onclick attribute in HTML:
<input onclick="clickME(event)" ...>
Check out this fiddle:
https://jsfiddle.net/57js0ps7/2/
You need to maintain a counter per each button individually - use an array to keep track of how many times a button has been clicked. If you don't the clicks var in your code will be two when you select 2 buttons and reset.
On your html:
lets say you have 50 of these
<button type="button" data-clicked="false">1</button>
<button type="button" data-clicked="false">2</button>
and on your javascript
var buttons = document.querySelectorAll('button');
buttons.forEach(function(button) {
button.addEventListener('click', function() {
if (this.dataset.clicked == 'false') {
this.dataset.clicked = 'true';
this.innerHTML = parseInt(this.innerHTML) + 1;
}
else {
this.dataset.clicked = 'false'
this.innerHTML = parseInt(this.innerHTML) - 1;
}
})
});
EDIT: Here is a working fiddle
Since you have this tagged as jQuery here is a solution using jQuery. The solution involves using the data- attribute to hold the click count for each button (input). Not sure why you use inputs instead of buttons, but I kept that the same
It also has a getTotal() function that goes through each element and tallies the click to see how many slots were selected and displays that number for you.
$(document).ready(function() {
$(".btn").on("click", clickME);
});
function clickME() {
var clicks = $(this).data("clicks");
var newClicks = parseInt(clicks) + 1;
if(newClicks > 1){
newClicks = 0;
}
// set the new click count on the element
$(this).data("clicks", newClicks);
setTotal();
}
function setTotal(){
var total = 0;
$(".btn").each(function(imdex, btn) {
var currClicks = parseInt($(btn).data("clicks"));
total += currClicks;
});
$("#clicks").text(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="Button" class="btn" data-clicks=0 value="0" />
<input type="Button" class="btn" data-clicks=0 value="1" />
<input type="Button" class="btn" data-clicks=0 value="2" />
<input type="Button" class="btn" data-clicks=0 value="3" />
<input type="Button" class="btn" data-clicks=0 value="4" />
<input type="Button" class="btn" data-clicks=0 value="5" />
<input type="Button" class="btn" data-clicks=0 value="6" />
<div>
<p>You've choose <a id="clicks">0</a> slot/s.</p>
</div>

Javascript - check/uncheck checkbox after summing different inputs

I have a ‘parent’ <div>, and ‘child’ divs which are shown after clicking parent <div>.
All divs have <checkboxes> and <input> to put quantity.
Parent <checkbox> checks when at least one child <checkbox> is checked.
When child <checkbox> is checked/unchecked the quantity in <input> is automatically changed into ‘1’ or ‘’.
Parent quantity <input> is disabled and it is supposed to show the sum of all children quantities.
I have two problems.
First, the summing script works fine when you enter the quantity yourself, however when the quantity appears/disappears itself (after checking/unchecking the child <checkbox>) the summing script does not react on such change.
Secondly I wasn’t able to uncheck the parent <checkbox> when all child checkboxes are unchecked.
However I’m assuming if the summing script will start working properly I will be able to bind the parent <checkbox> with the sum (if (sum> 0){ $('#checkbox0').prop('checked', true);}else{$('#checkbox0').prop('checked', false);}
Html:
<div class="divCell" id="click1">
<div class="checkbox_div" style='pointer-events:none;'>
<input type="checkbox" id="checkbox0">
</div>
<div class="div_name_divcell">Parent - click to open</div>
<div class="div_quantity_divcell">
<input type="text" name="parent_1" class="quantity_class_parent_1" id="quantity_parent_1" size="1" maxlength="3" onkeypress="return numbersonly(this, event)" disabled="disabled">
</div>
</div>
<div id="hidden1" style="display: none;">
<div class="divCell" id="child_click1">
<div class="checkbox_div">
<input type="checkbox" id="checkbox1">
</div>
<div class="div_name_divcell">Child1</div>
<div class="div_quantity_divcell">
<input type="text" name="child_1" class="quantity_class_child" id="quantity_child_1" size="1" maxlength="3" onkeypress="return numbersonly(this, event)">
</div>
</div>
<div class="divCell" id="child_click2">
<div class="checkbox_div">
<input type="checkbox" id="checkbox2">
</div>
<div class="div_name_divcell">Child2</div>
<div class="div_quantity_divcell">
<input type="text" name="child_1" class="quantity_class_child" id="quantity_child_2" size="1" maxlength="3" onkeypress="return numbersonly(this, event)">
</div>
</div>
</div>
Css:
.divCell {width: 500px;height: 35px;margin: 2px 0;display: inline-block;background-color: #D4F78F;}
.div_quantity_divcell{float:right; padding:9px 1px 0 0}
.checkbox_div {width: 25px;position: relative;margin: 5px;float: left;}
.div_name_divcell {line-height: 35px;width: auto;float: left;}
JavaScript:
$(document).ready( function() {
event.preventDefault();
$('#checkbox1').click(function() {
if(this.checked){
$('#checkbox0').prop('checked', this.checked);
$('#quantity_child_1').val('1')
}else{
$('#quantity_child_1').val('')
//$('#checkbox0').prop('checked', false);
}});
$('#quantity_child_1').keyup(function(){
$('#checkbox1').prop('checked', this.value > 0);
$('#checkbox0').prop('checked', true);
})
//second child
$('#checkbox2').click(function() {
if(this.checked){
$('#checkbox0').prop('checked', this.checked);
$('#quantity_child_2').val('1')
}else{
$('#quantity_child_2').val('')
//$('#checkbox0').prop('checked', false);
}});
$('#quantity_child_2').keyup(function(){
$('#checkbox2').prop('checked', this.value > 0);
$('#checkbox0').prop('checked', true);
})
});
// suming script
$(document).on('change', '.quantity_class_child', function(){
var sum = 0;
$('.quantity_class_child').each(function(){
sum += +$(this).val();
});
$('#quantity_parent_1').val(sum);
});
//opening script
$(document).ready(function() {
$('#click1').click(function() {
if ($('#hidden1').is(':hidden')) {
$('#hidden1').show(500);
} else {
$('#hidden1').hide(500);
}
});
});
JSFiddle: https://jsfiddle.net/mamzj4tw/6/
This is an updated version of your version
https://jsfiddle.net/mamzj4tw/13/
It uses each() to better (and clean) add actions to inputs.
You can create your custom events like do-sum and fire when you want.
In this case I defined that the sum is executed when
$(document).trigger('do-sum');
fires do-sum event.
and I've set a listener that executes your routine:
$(document).on('do-sum', function(){
var sum = 0;
$('.quantity_class_child.active').each(function(){
sum += +$(this).val();
});
$('#quantity_parent_1').val(sum);
var parentChecked = false;
$('#hidden1 input[type="checkbox"]').each(function(i, e){
if($(e).is(':checked')) {
parentChecked = true;
}
});
$('#checkbox0').prop('checked', parentChecked);
});
I also use class active to set valid inputs (and quick sum them).
PS you don't need event.preventDefault(); after document ready event.
Ok, Here are the things that you can do to achieve,
First, the summing script works fine when you enter the quantity yourself, however when the quantity appears/disappears itself (after checking/unchecking the child ) the summing script does not react on such change.
The thing is change event will not be triggered if you are setting/changing the value from the javascript. For this you can manually call the change event to trigger the effect. Or, Create a separate function for summation calculation and call it on uncheck event of the checkbox.
eg.
Either
$('#checkbox1').click(function() {
if (this.checked) {
$('#checkbox0').prop('checked', this.checked);
$('#quantity_child_1').val('1')
} else {
$('#quantity_child_1').val('')
$(".quantity_class_child").trigger("change");
//$('#checkbox0').prop('checked', false);
}
});
OR
$('#checkbox1').click(function() {
if (this.checked) {
$('#checkbox0').prop('checked', this.checked);
$('#quantity_child_1').val('1')
} else {
$('#quantity_child_1').val('');
summation();
}
});
function summation(){
var sum = 0;
$('.quantity_class_child').each(function() {
sum += +$(this).val();
});
$('#quantity_parent_1').val(sum);
}
Now for the second part,
Secondly I wasn’t able to uncheck the parent when all child checkboxes are unchecked.
Just check the length of the checked input box during the summation process and uncheck it if the the length is zero.
Hope this help you cause.
Your code was a bit to complicated, so i have rewritten what you tried to archive ( without the css part). fiddle here
three little html div's
<div class="parent" id="parent">
<span class="input">
<input type="checkbox" name="parent" value="">
<label for parent>parent - click to open</label>
<input type="text" name="sum">
</span>
</div>
<div class="child" id="child1">
<span class="input">
<input type="checkbox" class="inputCheckbox" name="child1" value="child1">
<input type="text" class="inputSum" name="sum1">
</span>
</div>
<div class="child" id="child2">
<span class="input">
<input type="checkbox" class="inputCheckbox" name="child2" value="child2">
<input type="text" class="inputSum" name="sum2">
</span>
</div>
and a bit of jquery
$('.child').hide();
// check if parent checkbox is checked
$('input[name="parent"]').click ( function () {
if ( $(this).is(':checked') ) $('.child').show(); else $('.child').hide();
})
// check if childcheckbox is checked , if true trigger keyup and sum
$('.inputCheckbox').on ( 'change', function () {
if ( $(this).is(':checked') ) $(this).next().val('1').keyup();
// if not , trigger parent
if ( ! $('.inputCheckbox').is(':checked') ) $('input[name="parent"]').click ();
})
// check if value is entered and sum it on keyup
$('.inputSum').on('keyup', function () {
var sum = 0;
$('.inputSum').each ( function () { sum += ( $(this).val() - 0) })
$('input[name="sum"]').val(sum)
})
HTH
You can add new elements https://jsfiddle.net/mamzj4tw/34/
$(document).ready( function() {
$('.drop-down #checkbox').on('change',function(){
$(this).closest('.divCell').find('#quantity_child')
.val(this.checked ? 1:'').trigger('keyup');
});
$(document).on('keyup click', '.quantity_class_child', function(){
$(this).closest('.divCell').find('#checkbox').prop("checked",+$(this).val());
var sum = 0;
$('.quantity_class_child').each(function(){sum += +$(this).val()});
$('#quantity_parent_1').val(sum ||'');
$('#checkbox0').prop("checked", sum);
});
$('#click1').click(function() { $('#hidden1').toggle(500); });
});

Adding new text box using javascript

I have a webpage. There is a button called add. When this add button is clicked then 1 text box must be added. This should happen at client side only.
I want to allow the user to add at most 10 text boxes.
How can I achieve it using javascript?
example:
only 1 text box is displayed
user click add >
2 text boxes displayed
user clicks add >
I also wants to provide a button called "remove" by which the user can remove the extra text box
Can anyone provide me a javascript code for this??
Untested, but this should work (assuming an element with the right id exists);
var add_input = function () {
var count = 0;
return function add_input() {
count++;
if (count >= 10) {
return false;
}
var input = document.createElement('input');
input.name = 'generated_input';
document.getElementbyId('inputs_contained').appendChild(input);
}
}();
add_input();
add_input();
add_input();
A solution using the jQuery framework:
<form>
<ul class="addedfields">
<li><input type="text" name="field[]" class="textbox" />
<input type="button" class="removebutton" value="remove"/></li>
</ul>
<input type="button" class="addbutton" value="add"/>
</form>
The jQuery script code:
$(function(){
$(".addbutton").click(){
if(".addedfields").length < 10){
$(".addedfields").append(
'<li><input type="text" name="field[]" class="textbox" />' +
'<input type="button" class="removebutton" value="remove"/></li>'
);
}
}
// live event will automatically be attached to every new remove button
$(".removebutton").live("click",function(){
$(this).parent().remove();
});
});
Note: I did not test the code.
Edit: changed faulty quotation marks
I hope you are using jQuery.
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript"><!--
$(document).ready(function(){
var counter = 2;
$("#add").click(function () {
if(counter==11){
alert("Too many boxes");
return false;
}
$("#textBoxes").html($("#textBoxes").html() + "<div id='d"+counter+"' ><label for='t2'> Textbox "+counter+"</label><input type='textbox' id='t"+counter+"' > </div>\n");
++counter;
});
$("#remove").click(function () {
if(counter==1){
alert("Can u see any boxes");
return false;
}
--counter;
$("#d"+counter).remove();
});
});
// --></script>
</head><body>
<div id='textBoxes'>
<div id='d1' ><label for="t1"> Textbox 1</label><input type='textbox' id='t1' ></div>
</div>
<input type='button' value='add' id='add'>
<input type='button' value='remove' id='remove'>

Categories

Resources