Jquery closest does not work? - javascript

I'm trying to build a general function that get's called from four different checkboxes. When the checkbox is checked it should remove the attribute disabled from a button near the checkbox.
my buttons all have diffrent classes like this
button 1: class="button primary pie list-buy-button list_buy_button_1903"
button 2: class="button primary pie list-buy-button list_buy_button_1901"
button 3: class="button primary pie list-buy-button list_buy_button_1899"
button 4: class="button primary pie list-buy-button list_buy_button_1897"
first i bind the event to my checkboxes
$(".avtalsbox").each(function()
{
$(this).click(function()
{
chbclickeventhandler(this);
});
});
then i handle it with this function.. this i where i encounter a problem
i have tried many solutions but noone works?
function chbclickeventhandler(thebox)
{
if (thebox.checked) {
//SOLUTION 1
var button = $(thebox).closest("[class*='buy_button']");
$(button).removeAttr("disabled");
//SOLUTION 2
var button = $(thebox).parent().children("[class*='buy_button']");
$(button ).removeAttr("disabled");
}
}
this is how my html looks like
<div class="buyonly boxhighlight varmepaket1">
<div width="100%" style="float:right;">
<!---köpknapp--->
<form class="product_form" action="/shoppingcart/increase_product_count/" method="post">
<input type="hidden" name="quantity" value="1" id="quantity">
<span class="button-container pie">
<!-- THIS IS THE INPUT I WANT TO REMOVE DISABLED FROM ASWELL AS ADD IT -->
<input class="button primary pie list-buy-button list_buy_button_1903" type="submit" value="Beställ idag!" disabled="">
</span>
<!---crap--->
<input type="hidden" name="product_id" value="1903">
<input type="hidden" name="article_number" value="varmepaket2">
</form>
<!---köpknapp END--->
</div>
<div width="" style="float:right;">
<a href="#" onclick="eb_klarna_sum=14990; $('body').find('#klarna_payment').click(); return false;">
<img class="symbol" src="/layouts/focus/klarna_symbol.png"> Dela upp betalningen från xxx kr/mån</a></div>
<div style="float:left;"><input type="checkbox" class="avtalsbox" name="godkannavtalet" value="varmepaket1">Jag godkänner avtalet!</div>
</div>

Your usage of closest is incorrect try this way: Closest will only get you to the parent or itself provided there is a match in the selector. So here use closest to get to the parent div with the class .buyonly and find for the button inside that.
$(".avtalsbox").change(chbclickeventhandler);
function chbclickeventhandler() {
if (this.checked) {
//SOLUTION 1
var button = $(this).closest(".buyonly").find("[class*='buy_button']");
$(button).prop("disabled", false);
}
}
Fiddle
If you are looking to toggle the button then you can just do:
$(".avtalsbox").change(chbclickeventhandler);
function chbclickeventhandler() {
$(this)
.closest(".buyonly")
.find("[class*='buy_button']")
.prop("disabled", !this.checked);
}

In your case checkbox is not a children of button, so you cannot use closest!

use
$(thebox).closest('.product_form').find(["class*='buy_button']");

Related

PHP & JQuery Adding Dynamic Inputs

I'm using Jquery in order to add dynamic inputs on my page. I only want to display one input initially, then more can be added by clicking a button.
This works as expected.
I'm then using PHP in order to catch the $_POST values of the inputs and send them to an external script. This also works, however I'm always receiving one extra item in my array, and it's empty.
I think this is because I have a hidden <div> field in my HTML, which is shown when a new input is generated?
My code is below;
HTML
// unnecessary code removed
<div class="after-add-more">
<button class="add-more" type="button" title="Add"></button>
<input name="addmore[]" value="" type="text">
</div>
<div class="copy-fields hide">
<div>
<button class="remove" type="button" title="Remove"></button>
<input type="text" name="addmore[]" value="">
</div>
</div>
JQUERY
$(document).ready(function() {
//here first get the contents of the div with name class copy-fields and add it to after "after-add-more" div class.
$(".add-more").click(function() {
var html = $(".copy-fields").html();
$(".after-add-more").after(html);
});
//here it will remove the current value of the remove button which has been pressed
$("body").on("click", ".remove", function() {
$(this).parents(".control-group").remove();
});
});
PHP
<?php
// unnecessary code removed
$field_values_array = $_POST['addmore'];
?>
Without generating an additional input, I enter 1111111 into the input box and submit. A print_r($_POST) produces;
[addmore] => Array
(
[0] => 1111111
[1] =>
)
Any help is appreciated.
You are probably better just getting the parent of the element that was clicked and adding your markup after that. Here is an example:
$(document).ready(function() {
// this function handles the click event
function addField(parent) {
// find your template, in this case its the first .after-add-more
var html = $(".after-add-more").first().clone();
// reset the value of any inputs
$('input', html).val('');
// wire the click handler for the button
$("button", html).click(function() {
addField($(this).parent());
});
// append it to the parent of the parent, addContainer
html.appendTo(parent.parent());
}
// wire the click handler for the add-more button
$(".add-more").click(function() {
addField($(this).parent());
});
// I don't know what the intention of this code is so I'm leaving it alone
$("body").on("click", ".remove", function() {
$(this).parents(".control-group").remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
// unnecessary code removed
<div id="addContainer">
<div class="after-add-more">
<button class="add-more" type="button" title="Add">Add</button>
<input name="addmore[]" value="" type="text">
</div>
</div>
<div class="copy-fields hide">
<div>
<button class="remove" type="button" title="Remove">Remove</button>
<input type="text" name="addmore[]" value="">
</div>
</div>

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 remove space after using remove() function jquery

I'm making reminder app here is the interface
Now when i click the "All Checked" button all the check boxes removes. I'm using remove() function for that but after removing these check boxes the space remains there, and when I'm putting the new value it's coming after that space. I was trying trim function but its not working
MY HTML
<div class="has-success topSpaceFromRoof">
<div class="checkbox">
</div>
</div>
<button class="btn btn-default btn-block slight" id="allFinished">
ALL Checked
</button>
MY JAVASCRIPT
$('#allFinished').click(function(){
$('span').remove();
$('.checkbox').trim();
});
MY JAVASCRIPT FOR INPUT VALUES
$('<label><span>' +
'<input type="checkbox" id="checkboxSuccess" value="option1">' +
input.val().toUpperCase() +
'</span></label><br/>').appendTo('.checkbox');
event.preventDefault();
Looks Like This
Try this,
$('#allFinished').click(function(){
$('span').remove();
$('.checkbox').html('');
});
Another option you can use by using some CSS like,
.checkbox label{
display:inline-block;
margin:2px 0;
}
And no need to add <br/> after your dynamically added label's.
And some jquery code like,
$('#allFinished').click(function(){
$('.checkbox label').remove();
});
Try
$('#allFinished').click(function(){
$('.checkbox').find('*').remove();
// $('.checkbox').empty();
});
Please try this :
Use .empty(); method
$('#allFinished').click(function(){
$('span').empty();
});
Reference
Demo
This is what you need to code
DEMO
HTML
<input type=text />
<input type=button value=Submit />
<div class="has-success topSpaceFromRoof">
<div class="checkbox">
</div>
</div>
<button class="btn btn-default btn-block slight" id="allFinished">
ALL Checked
</button>
CODE
$(document).ready(function(){
$('#allFinished').click(function(){
$('span').remove();
$('.checkbox').empty();
});
$(":button[value=Submit]").click(function(){
var input=$(":text");
$('<label><span>' + '<input type="checkbox" id="checkboxSuccess" value="option1">' + input.val().toUpperCase() + '</span></label><br/>').appendTo('.checkbox');
});
});
Think about your markup first. Try to come up with a structure which allows you identify a whole block of your checkboxes with its label, the input itself and whatever element you want to associate with this checkbox.
Something like this:
<div class="checkbox-wrapper">
<label>
Blablub
<input type="checkbox" value="1" />
</label>
</div>
Now in your click event you could loop through all your checkboxes (elements with your identifiying class checkbox-wrapper) and remove the whole element if its checkbox is checked:
$(document).ready(function(){
$('#allFinished').on("click", function(){
$(".checkbox-wrapper").each(function(){
if($(this).find("input[type=checkbox]").prop("checked")){
$(this).remove();
}
});
});
});
Working Demo: https://jsfiddle.net/n1o3t3nz/1/

Angularjs removing dynamically generated rows

I have following html and Angularjs controller code to add rows dynamically.
<form name="{{form.name}}"
ng-repeat="form in forms">
<h2>{{form.name}}</h2>
<div ng-repeat="(i,cont) in form.contacts">
<input type="text" class="xdTextBox" ng-model="cont.ac"/>
<input type="text" class="xdTextBox" ng-model="cont.a_number"/>
<input type="text" class="xdTextBox" ng-model="cont.p_id"/>
</div>
<button ng-click="submit(form)">Submit</button>
<button ng-click="addFields(form)">Add</button>
<hr>
</form>
Controller code to add rowsis
$scope.addFields = function (form) {
if (typeof form.contacts == 'undefined') {
form.contacts = [];
}
form.contacts.push({name:'', ac: '', a_number: '', p_id: '' });
}
What I want to do next is after adding rows if i mouse over any row a delete link or button shows up and if one clicks it, it removes that row.
Here is the working plunker for the adding rows.
http://plnkr.co/edit/9bUnd7t0PyMwykgi0VZR?p=preview
Please let me know how I can mouse over a row and click the remove button or link to remove that list.
Thanks
Take a look here:
http://plnkr.co/edit/zxjHLzqiAQnZzcaUwgBL?p=preview
I added the "contact" class to the div container so I could identify it in the CSS:
<div ng-repeat="(i,cont) in form.contacts" class="contact">
I added the remove button inside the container and gave it the "remove" class:
<button type="button" class="remove" ng-click="form.contacts.splice(i, 1);">Remove</button>
(Note: You may wish to have a function inside your scope for removing a contact if you need to do anything more complicated than just removing it from the array.)
To get the button to be hidden initially, but show up when you hover over the row, I used the following CSS:
.contact .remove { visibility: hidden; }
.contact:hover .remove { visibility: visible; }
You can do it by adding a function to your scope that recieves the form and index, then splicing the desired index out of it:
<div ng-repeat="(i,cont) in form.contacts">
<input type="text" class="xdTextBox" ng-model="cont.ac"/>
<input type="text" class="xdTextBox" ng-model="cont.a_number"/>
<input type="text" class="xdTextBox" ng-model="cont.p_id"/>
<button ng-click="delete(form, i)">Delete</button>
</div>
Then, the Javascript (add this to your controller):
$scope.delete = function(form, index) {
form.contacts.splice(index, 1);
}
http://plnkr.co/edit/2SEGDnGoE7kaw0KvOpKr?p=preview

Show/hide forms using buttons and JavaScript

I need to show a form using a button, and hide it when the user presses another button, because the other button shows another form. I did a similar thing with a select box, but I can't figure out how to do this.
Use the following code fragment to hide the form on button click.
document.getElementById("your form id").style.display="none";
And the following code to display it:
document.getElementById("your form id").style.display="block";
Or you can use the same function for both purposes:
function asd(a)
{
if(a==1)
document.getElementById("asd").style.display="none";
else
document.getElementById("asd").style.display="block";
}
And the HTML:
<form id="asd">form </form>
<button onclick="asd(1)">Hide</button>
<button onclick="asd(2)">Show</button>
There's something I bet you already heard about this! It's called jQuery.
$("#button1").click(function() {
$("#form1").show();
};
It's really easy and you can use CSS-like selectors and you can add animations. It's really easy to learn.
If you have a container and two sub containers, you can do like this
jQuery
$("#previousbutton").click(function() {
$("#form_sub_container1").show();
$("#form_sub_container2").hide(); })
$("#nextbutton").click(function() {
$("#form_container").find(":hidden").show().next();
$("#form_sub_container1").hide();
})
HTML
<div id="form_container">
<div id="form_sub_container1" style="display: block;">
</div>
<div id="form_sub_container2" style="display: none;">
</div>
</div>
There's the global attribute called hidden. But I'm green to all this and maybe there was a reason it wasn't mentioned yet?
var someCondition = true;
if (someCondition == true){
document.getElementById('hidden div').hidden = false;
}
<div id="hidden div" hidden>
stuff hidden by default
</div>
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/hidden
Would you want the same form with different parts, showing each part accordingly with a button?
Here an example with three steps, that is, three form parts, but it is expandable to any number of form parts. The HTML characters « and » just print respectively « and » which might be interesting for the previous and next button characters.
shows_form_part(1)
/* this function shows form part [n] and hides the remaining form parts */
function shows_form_part(n){
var i = 1, p = document.getElementById("form_part"+1);
while (p !== null){
if (i === n){
p.style.display = "";
}
else{
p.style.display = "none";
}
i++;
p = document.getElementById("form_part"+i);
}
}
/* this is called at the last step using info filled during the previous steps*/
function calc_sum() {
var sum =
parseInt(document.getElementById("num1").value) +
parseInt(document.getElementById("num2").value) +
parseInt(document.getElementById("num3").value);
alert("The sum is: " + sum);
}
<div id="form_part1">
Part 1<br>
<input type="number" value="1" id="num1"><br>
<button type="button" onclick="shows_form_part(2)">»</button>
</div>
<div id="form_part2">
Part 2<br>
<input type="number" value="2" id="num2"><br>
<button type="button" onclick="shows_form_part(1)">«</button>
<button type="button" onclick="shows_form_part(3)">»</button>
</div>
<div id="form_part3">
Part 3<br>
<input type="number" value="3" id="num3"><br>
<button type="button" onclick="shows_form_part(2)">«</button>
<button type="button" onclick="calc_sum()">Sum</button>
</div>

Categories

Resources