Select all checkbox only works some of the time - javascript

I have a form with checkboxes, along with a hidden select all button inside the form. I use jQuery to listen for a button click outside the form, and then "click" the hidden button element to select all. Sometimes the page loads up and I click the button and it works perfectly. You can click it multiple times and they all check and uncheck as intended. The form submits perfectly.
Other times, however, the page will load up and I click the button and nothing happens. They don't check no matter how many times I click. I've found this happens a lot if the page sits for more than maybe 10 seconds without me doing anything. But it also can happen on page load. I can't understand why. Is there an error in my code somewhere that I'm just not seeing?
$(document).ready(function(){
$('#select-all').click(function(event) {
if(this.checked) {
// Iterate each checkbox
$(':checkbox').each(function() {
this.checked = true;
$('label.choice').toggleClass("choice-text-color");
});
} else {
$(':checkbox').each(function() {
this.checked = false;
$('label.choice').toggleClass("choice-text-color");
});
}
});
$("#selectAll").click(function() {
$('#select-all').click()
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="selectAll" class="btn btn-secondary my-2 my-sm-0"
type="button" name="selectAll">Select All</button>
<form>
<input type="checkbox" id="1"><label for="1" class="choice">ABC</label>
<input type="checkbox" id="2"><label for="2" class="choice">DEF</label>
(....etc.....)
<input type="checkbox" id="select-all" style="display: none;">
<input type="submit" style="display: none;">
</form>

It seems to me that your issue is due to the extraneous markup you've added to facilitate the select all functionality and the JavaScript/JQuery tied to it.
All you need is a single button (it doesn't matter whether it's part of the form or not) to trigger the select/deselect operations. Also, since the button will not be transmitting any data as part of the form the name attribute should not be used.
Also, if you don't want users to see the form's submit button, then simply don't add one to the form. You can then programmatically submit the form with $(form).submit().
// Passing a function into JQuery is the same as document.ready
$(function(){
// JQuery recommends the use of "on" to bind events
$('#selectAll').on("click", function(event) {
$(':checkbox').each(function() {
this.checked = true;
});
$('label.choice').addClass("choice-text-color"); // Update the class use
});
});
.choice-text-color {
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="selectAll" class="btn btn-secondary my-2 my-sm-0" type="button">Select All</button>
<form>
<input type="checkbox" id="1"><label for="1" class="choice">ABC</label>
<input type="checkbox" id="2"><label for="2" class="choice">DEF</label>
</form>

Related

how to store radio button value in sessionStorage with jquery

I have radio button in my navbar and I want to store its value for one session or I can say it automatically retains the same value as user visits different pages of website but resets when browser or tab is closed. What I found is sessionStorage and I tried it but unfortunately its not working, here is my code
<lab
console.log($('[type=radio]').length);
$("#option1").click(function() {
console.log('I am inside radio type'+this.value);
sessionStorage.setItem('option', this.value);
});
$("#option2").click(function() {
console.log('I am inside radio type'+this.value);
sessionStorage.setItem('option', this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- <div class="btn-group btn-group-toggle" data-toggle="buttons"> -->
<!-- <label class="btn btn-secondary active"> -->
<input type="radio" value="shop" name="option" id="option1">option1
<!-- </label> -->
<!-- <label class="btn btn-secondary"> -->
<input type="radio" value="product" name="option" id="option2">option2
<!-- </label> -->
<!-- </div> -->
el class="btn btn-secondary active">
Option1
Option2
In script what I tried is
$('[type=radio]').click(function() {
var value = $('[name="option"]').val();
sessionStorage.setItem('option',value);
});
console.log(sessionStorage.getItem('option'));
Its only printing option1 every time and is it the right way what I want to achieve ?
The type value needs to be formatted as a string with quotes around it, like below:
$('input[type="radio"]').click(function() {
console.log('I am inside radio type');
sessionStorage.setItem('option', this.value);
});
And if you're loading these buttons dynamically/after loading the script, you can attach the listener to the document object instead:
$(document).on('click', 'input[type="radio"]', function() {
console.log('I am inside radio type');
sessionStorage.setItem('option', this.value);
});
Inside the click event store the value of checked radio button as follows,
$(function() {
alert(sessionStorage.getItem('option'));
$('[type=radio]').click(function() {
alert(this.value); sessionStorage.setItem('option',this.value);
});
});

checkbox change not fired at page load time

I have a button and checkbox(terms of use) in my page.
The button should be disabled if the checkbox is not checked.
I want to reset the situation in every load. (first load or using back btn or etc) the reset state is: checkbox shouldn't be checked, and btn is disabled.
But the function is called just when I click the checkbox, and not at load time.
Update: Also I tested .trigger('change'), too. It did't work too
$(function() {
$('#termsOfUse').removeAttr('checked');
$('#termsOfUse').change();
$('#termsOfUse').change(function() {
if ($(this).is(":checked")) {
$('#createBtn').prop('disabled', false);
} else {
$('#createBtn').prop('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<input id="termsOfUse" type="checkbox" />
<label for="termsOfUse" style="display: inline;">
<span>rules</span> I am agree with</label>
</div>
<div class="create">
<input id="createBtn" type="button" value="create" class="btn btn-default btn-success"
onclick="location.href = '#Url.Action("Create","NewOne ")'" />
</div>
You are calling the .change before you assign.
$(function() {
$('#termsOfUse').prop('checked',false);
$('#termsOfUse').change(function() {
$('#createBtn').prop('disabled', !this.checked);
}).change(); // execute at load
});
You can also put
<script>
$('#termsOfUse').prop('checked',false);
$('#termsOfUse').change(function() {
$('#createBtn').prop('disabled', !this.checked);
}).change(); // execute at load
</script>
</body>
at the end of your document

HTML Selectable table with edit/delete/view options

I have table, where you can select table rows, and it passes the information to modal window. But there is problem, I want the popup window to show error if there is no row selected
Button to edit row
<a class="icon icon-pencil js-popup js-tooltip" href="#edit" title="Edit selected row"></a>
JavaScript Code
$(document).on('click', '#table_contactgroups tbody tr', function(e) {
$(this).addClass('selected').siblings().removeClass('selected');
var name = $(this).find('td:first').html();
var id = $(this).attr('id');
$('#edit input[name="name"]').val(name)
$('#edit input[name="id"]').val(id)
$("#name").text(name);
$('#delete input[name="id"]').val(id)
});
Modal
<div id="edit">
<h2 class="text-center ls-large">Edit contact group</h2>
<form class="js-ajax-form" data-ajax-form="edit=a.logged-in;editFrom=
<?php echo URL_BASE; ?>template/header.php"
name="contacts-form" method="post"
action="<?php echo URL_BASE; ?>contactgroups/contactgroup_manager.php?a=edit">
<fieldset>
<!-- <input type="text" name="name" placeholder="Name">-->
<div class="input-wrap">
<input type="text" name="name" maxlength="45" value="" placeholder="Name">
</div>
<input type="hidden" name="id" value="">
</fieldset>
<div class="controls multiple">
<button class="btn btn-default btn-small" type="submit" name="Edit" value="Edit">Submit</button>
<a class="btn btn-unimportant btn-small js-popup-close" href="#">Cancel</a>
</div>
</form>
</div>
There are two ways you could go with this.
Disable the edit button when no rows are selected.
Display an error when the edit button is pressed with no rows selected.
Arguably the first one is more user-friendly since it stops them making an unnecessary click.
In either case, you need to ensure a row is selected. So if you disable your edit button at page load like this using the disabled attribute:
<button type="button" id="EditButton" disabled>Edit</button>
Then in your existing function which runs when the user clicks on a row, you can enable it, since you now have a selected row:
$(document).on('click', '#table_contactgroups tbody tr', function(e) {
//...
$("#EditButton").prop('disabled', false);
});
That way, if there are no rows, the button never gets enabled.
N.B. I notice your Edit "button" is actually a hyperlink. If you want to continue using that, this answer may be helpful in determining how to enable/disable it : Disable link using css. Otherwise you might be better to replace it with a button, or hide it instead. It's more difficult to make hyperlinks unclickable.
If you want to go down route 2, and display an error message when no row is selected, you'll have to handle the click event of the hyperlink. First, give it an id.
<a id="EditLink" class="icon icon-pencil js-popup js-tooltip" href="#edit" title="Edit selected row"></a>
Then handle the click, and check for selected rows. Since you're using the ".selected" class to denote a selected row, this is fairly easy to test for.
$("#EditLink").click(function(event) {
if ($(".selected").length == 0)
{
event.preventDefault(); //stops the normal click behaviour from occurring
alert("Please select a row to edit");
}
});

How to submit a form using JQuery depending on which option a user chooses

I've looked around at a few different questions with regards to this topic and no breakthroughts. What I'm trying to do is when the user clicks on the submit button I show 3 buttons on the screen and if the user clicks the third button the form submits. Otherwise I prevent the form from submitting.
However I'm having trouble implementing this. Currently I'm doing it this way and from my research i saw the very obvious mistake I was making with calling e.preventDefault() as soon as the form is submitted which prevents it from being able to be submit.
Hopefully in my code you will see what I'm trying to do. Show the three options before the form is submit and only submit if the third option is selected.
HTML:
<form action="some_url" method="post">
<input type="text" value="" id="fname" />
<input type="submit" value="Submit" />
</form>
<br/>
<div id="option-box">
<span id="option-a">Option A</span>
<span id="option-b">Option B</span>
<span id="option-c">Option C</span>
</div>
JQuery:
$('form').submit(function (e) {
e.preventDefault();
$('#option-box').show();
$('#option-a').click(function () {
alert('option a');
//Do something else
});
$('#option-b').click(function () {
alert('option b');
//Do something else
});
$('#option-c').click(function () {
alert('option c - SUBMIT');
$('form').submit();
});
});
#option-box {
display: none;
}
#option-box span {
background:green;
color: white;
display: block;
cursor: pointer;
padding:5px;
margin: 10px 0;
text-align:center;
max-width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form action="some_url" method="post">
<input type="text" value="" id="fname" />
<input type="submit" value="Submit" />
</form>
<br/>
<div id="option-box">
<span id="option-a">Option A</span>
<span id="option-b">Option B</span>
<span id="option-c">Option C</span>
</div>
Here is a fiddle of my current code:
https://jsfiddle.net/javacadabra/rb553ttw/1/
You need to prevent submitting the form to start
$('form').submit(function (e) {
e.preventDefault(); //<-- Need this
//... other code
});
Adding event handlers inside another action can also lead to issues. Submit more than once, you will have more event handlers attached. So you need to remove previous events. You can remove them with off
$('#option-a').off("click").on("click", function () { /* other code */ });
Lastly you should not need to cancel the default action of the buttons since they should not do anything.
And if you want to submit the form, you probably want to unbind the submit method or call it from DOM directly.
$('form').off("submit").submit();
or
$('form')[0].submit();
Take note of what the last selection was, and preventDefault based on that selection:
var selectedOption = "";
$('form').submit(function (e) {
$('#option-box').show();
if (selectedOption != "option-c") {
e.preventDefault();
}
});
$('#option-box').on('click', 'span', function () {
selectedOption = $(this).attr("id");
});
JSFiddle: https://jsfiddle.net/TrueBlueAussie/rb553ttw/4/
There are a few ways I can think of for the solution.
1. Remove type="submit"
Here instead of making <button type="submit"> you can make it <button type="button"> which does not submit the form unless you specify it in your script on click event listener $('form').submit()
2. Activate button on choosing option
Here your submit button is initially disabled. You can call the function using onClick event on the option or in the script and remove the disabled property of the button
3. Apply form action url on choosing option
Similar to 2nd option, here you will set the action url when the user selects a particular option using the script. In case user selects any other option and clicks on submit, no action will be performed

Multiple JavasScript submits in the same form

When I click on submit1 and then on submit2 everything is going well, but, when I press Enter Key on 1st input text I go to the second part
When I press Enter Key on the 2nd input text -> 1st JavaScript function executes which causes me trouble.
I don't want to disable Enter Key press, but that he executes the good submit input.
Is there a way to deactivate submit1 after he has been executed?
Or know from which input text Enter Key has been pressed?
HTML:
<div id="1">
<input type="text" placeholder="name"/>
</div>
<div id="2">
<input type="submit" value="submit" id="submit1"/>
</div>
<div id="3">
<input type="text" placeholder="firstname"/>
</div>
<div id="4">
<input type="submit" value="submit" id="submit2"/>
</div>
CSS:
#3, #4
{
display: none;
}
JavaScript:
$(document).ready(function() {
$("#submit1").click(function () {
/* Verify data with javascript and send it with Ajax */
/* if everything is ok display: */
document.querySelector("#2").style.display = "none";
document.querySelector("#3").style.display = "block";
document.querySelector("#4").style.display = "block";
});
$("#submit2").click(function () {
/* Verify data with javascript and send it with Ajax */
});
});
Unless I misunderstood the question - you are simply trying to make sure that the correct event handler gets called based on which button is selected by the user. This will work fine as long as the buttons have unique IDs which they do - and you can associate them with the correct event handler (which it seems like you are doing in the shared code).
Also, you can disable any button using the disabled attribute (set it to true).
to disable
document.getElementById("submit1").disabled = true;
to enable:
document.getElementById("submit1").disabled = false;
From what I can tell your biggest problem here is that you seem to have two submit buttons in a single form tag. I would seriously recommend against this as it can cause issues like the one you are experiencing. Instead I would change both to buttons and add the submit functionality to JavaScript methods as you are kind of doing now.
Obviously though you would want to link the text boxes to a button then and for that I would take a look at this SO question How to trigger HTML button when you press Enter in textbox?
<input type="submit"> is a special control. It will cause the form to submit if the form has focus and the enter button is pressed. When using this you should make use of event.preventDefault() to cancel that behavior when binding to the click event. I suggest using <button type="button"><button> instead.
If you press ENTER on submit1, submit2 will not be selected unless you hit TAB. Are you doing this?
Anyway, you can do this:
$("#submit1").click(function () {
/* Verify data with javascript and send it with Ajax */
/* if everything is ok display: */
$("#submit2").focus(); // This will automatically focus the user on the second submit button //
});
This will force the user, the next time he hits ENTER, to submit the submit2 button.
But don't use .submit()... you should use the .submit() function instead of .click(), because I believe .click() only checks for mouse clicks?
$("#submit1").submit(function(){
/* Blah blah blah... */
$("#submit2").focus(); // This will automatically focus the user on the second submit button //
});
$("#submit2").submit(function(){
/* ... */
});
As other users have said, are submit1 and submit2 in the same <form> tag:
Yes, they were. But you shouldn't have 2 fields in the same <form> tag if you want to submit the data separately.
Do this:
HTML
<form>
<div id="1">
<input type="text" placeholder="name"/>
</div>
<div id="2">
<input type="submit" value="submit" id="submit1"/>
</div>
</form>
<form>
<div id="3">
<input type="text" placeholder="firstname"/>
</div>
<div id="4">
<input type="submit" value="submit" id="submit2"/>
</div>
</form>
JQuery
$("#submit1").submit(function(e){
/* Blah blah blah... */
e.preventDefault(); // Keeps the user on the same page //
});
$("#submit2").submit(function(e){
/* ... */
e.preventDefault(); // Keeps the user on the same page //
});
I let it work like that:
Why should I have troubles with one form? IE < 6?
HTML:
<form>
<div id="1">
<input type="text" id="text1"/>
</div>
<div id="2">
<input type="submit" value="submit" id="submit1"/>
</div>
<div id="3">
<input type="text" id="text2"/>
</div>
<div id="4">
<input type="submit" value="submit" id="submit2"/>
</div>
</form>
CSS:
#3, #4
{
display: none;
}
JAVASCRIPT:
$(document).ready(function() {
$('#text2').keypress(function(e){
if(e.keyCode==13)
$('#submit2').click();
});
$("#submit1").click(function () {
/* Verify data with javascript and send it with Ajax */
/* if everything is ok display: */
document.querySelector("#2").style.display = "none";
document.querySelector("#3").style.display = "block";
document.querySelector("#4").style.display = "block";
document.querySelector("#submit1").disabled = true;
});
$("#submit2").click(function () {
/* Verify data with javascript and send it with Ajax */
});
});

Categories

Resources