I have multiple input boxes with the attribute name="user[]"
When a button is clicked for a particular input I need to find out at what index of user was clicked.
I've tried a few method like .index(), .attr('name"), but I cant find out the index.
How is this possible?
<div>
<input type="hidden" name="user[]"> <!-- index 0 -->
<button class="btn btn-primary">
</div>
<div>
<input type="hidden" name="user[]"> <!-- index 1 -->
<button class="btn btn-primary">
</div>
<div>
<input type="hidden" name="user[]"> <!-- index 2 -->
<button class="btn btn-primary">
</div>
...
new div can be added by clicking a button.
This is used for a user invite form so there are no ids.
I need something like this
$('button').on('click', function() {
var index = $(this).parent().children('input').getTheIndex();
// where the index is defined by the use of []
});
jQuery's .index() finds the index of an element within the given collection.
So, to search among the name="user[]" inputs, you'll first need to find all of them:
var index = $(':text[name="user[]"]')...;
Then, you can determine the .index() of the current input among them:
var index = ...index(currentInput);
Example:
$('button').on('click', function() {
var allUsers = $('[name="user[]"]');
var user = $(this).siblings('[name="user[]"]');
var index = allUsers.index(user.get(0)); // get the native DOM node for the search
console.log(index); // 0, 1, ...
console.log(user.get(0) === allUsers.get(index)); // true
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="hidden" name="user[]"> <!-- index 0 -->
<button class="btn btn-primary">Test</button>
</div>
<div>
<input type="hidden" name="user[]"> <!-- index 1 -->
<button class="btn btn-primary">Test</button>
</div>
<div>
<input type="hidden" name="user[]"> <!-- index 2 -->
<button class="btn btn-primary">Test</button>
</div>
If the buttons each relate to a specific hidden element, this will do it:
var $users = $("input[type=hidden]");
var $buttons = $(".btn-primary");
$buttons.on("click", function(){
// Get the index of the button, since it will match the
// index of the input
alert("Button index was: " + $buttons.index(this));
// Get the index of the hidden element that comes just before the
// button that was clicked:
alert("Hidden index was: " + $users.index(this.previousElementSibling));
});
Fiddle: https://jsfiddle.net/cvnwr89p/5/
By the way, you need to close your <button> elements.
I think you need to set data attribute of that input boxes to the something like data-user-id=42 so you can look for checked boxes and get their data attribute. If you want something like "index within all form elements" than you need something like document.getElementById("form").elements where you can look for you inputs...
You could do this:
$('.btn-primary').on('click', function() {
console.log($('.btn-primary').index($(this)))
});
Related
I'm writing cart-box that will change the quantity of products in cart. It works only if I have one box (one product) in cart, but when I have more products in cart it changes the value of the first input only.
This is my html code (earlier in the code I've got loop for my products):
<div class="amount">
<a>
<button type="button" class="minus">-</button>
</a>
<input class="amount-input" th:type="text" th:value="1" th:min="1"/>
<a>
<button type="button" class="plus">+</button>
</a>
</div>
And this is JS code:
$('.minus').click(function () {
var parent = $(this).parent().parent();
var input = parseInt(parent.find(".amount-input").val());
var count = input - 1;
//input['value'] = count;
//parent.closest("input").value = count;
document.querySelector("input").value = count;
});
$('.plus').click(function () {
var parent = $(this).parent().parent();
var input = parseInt(parent.find(".amount-input").val());
var count = input + 1;
//input['value'] = count;
//parent.closest("input").value = count;
document.querySelector("input").value = count;
});
I know that document.querySelector("input").value = count changes the first input only, because it's first on the list, but input['value'] = count doesn't change anything, parent.closest("input").value = count either.
Make sure you use valid HTML, otherwise results are not guaranteed.
Next let's remove duplication and just use the one event listener for both buttons, changing the value added based on the presence of the plus class.
Finally, if you're using jQuery, stick to using jQuery methodology. Also, you are doing nothing here with jQuery that couldn't be done with simple, native, javascript.
//Use one event listener for both
$('.amount button').click(function () {
//Find the nearest ancestor with class amoun
var parent = $(this).closest(".amount");
//Note you need to still use $ with jQuery Objecyd
var input = $(parent).find(".amount-input");
//Set the count based on the class of the button click
var count = parseInt($(input).val()) + ($(this).hasClass("plus") ? 1 : -1 );
//Set the value
$(input).val(count);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="amount">
<button type="button" class="minus">-</button>
<input class="amount-input" type="text" value="1" min="1"/>
<button type="button" class="plus">+</button>
</div>
<div class="amount">
<button type="button" class="minus">-</button>
<input class="amount-input" type="text" value="1" min="1"/>
<button type="button" class="plus">+</button>
</div>
Hi i need to remove multiple files uploaded from an array based on user selection in javascript or angular.........
I have tried with below code
First we have a files that are uploaded in an array and is displayed in checkboxes as shown below in code
<div *ngFor="let image of uploadedImages" style="margin-left:10%" >
<label class="container" style="font-size:14px">
{{image.name}} ModifiedDate: {{image.lastModifiedDate}}
<input type="checkbox" style="float:left" value="{{image.name}}" id="lifecheck"
[name]="image.name">
<span class="checkmark"></span> <br><br>
</label>
</div>
<div style="padding-left:34px;padding-bottom:3px;">
<button *ngIf="imagefilename.length" class="btn btn-danger" style="width:200px;padding-left:30px" (click)="dropzone.reset();resetimage(image.Checked)">
Reset Selected files
</button>
</div>
The user will click on the checkboxes that are to be removed and the click on the button displayed and
it calls a function as displayed below
resetimage(imageName:any) {
for(var index = 0; index<this.uploadedImages.length;index++){
if(document.getElementByName("lifecheck")[i].checked==true){
this.uploadedImages.splice(index,1);
}
}
}
So in this function ,only first file in an array is getting removed where the user has selected multiple files to remove
So please help me if there is any solution
Expected result :
to remove multiple files uploaded from an array based on user selection in javascript or angular
Actual result :
Getting error
In your typescript document.getElementByName("lifecheck") cannot find the element in the dom hence you getting the error. In your dom you are creating dynamic input elements with id ='lifecheck'. This is already the wrong way of assigning ids, since dom ids must be unique.
So to fix this you can change your view to assign dynamic unique ids to your input elements:
<div *ngFor="let image of uploadedImages;let i=index" style="margin-left:10%" >
<label class="container" style="font-size:14px">
{{image.name}} ModifiedDate: {{image.lastModifiedDate}}
<input type="checkbox" style="float:left" value="{{image.name}}" id="lifecheck_{{i}}"
[name]="image.name">
<span class="checkmark"></span> <br><br>
</label>
</div>
<div style="padding-left:34px;padding-bottom:3px;">
<button *ngIf="imagefilename.length" class="btn btn-danger" style="width:200px;padding-left:30px" (click)="dropzone.reset();resetimage(image.Checked,i)">
Reset Selected files
</button>
So you are creating input elements with id= "lifecheck_1" etc. Then you can pass this id to your typescript function and find the element:
resetimage(imageName:any,id:number) {
for(var index = 0; index<this.uploadedImages.length;index++){
if(document.getElementById("lifecheck_" + id).checked==true){
this.uploadedImages.splice(index,1);
}
}
}
NOTE: this should be the way to fix your error;
I have a form that has three separate divs within it.
<form method="post">
<div id = "f1">
<div class="label">Value 1:</div>
<input type="text" name="name"/>
<button id = "next1" type="button" onclick="checkValue()">Next</button>
</div>
<div id ="f2">
<div class="label">Value 2:</div><br>
<input type="text" name="name"/>
<button type="button" onclick="checkValue()">Next</button><br>
</div>
<div id ="f3">
<div class="label">Value 3:</div><br>
<input type="text" name="name"/>
<button type="button" onclick="checkValue()">Next</button><br>
</div>
</div>
</form>
In my javascript function. I have a fadein and fadeout attached to each div when the next button is pressed. When the "next1" button is pressed the first div will be faded out and the second div will fade in. I want to check the values inputted in the first div when the user presses the first next button. I know how to do this if i just passed in the whole form into my javascript function on the final submit button, but I would like to know how to do this after each next button is pressed.
I also will have more than one value in each of the divs (f1, f2, f3) but for simplicity I only included one value.
EDIT*: further explaintaion
If i did this by passing in the form into checkValue. I could just do an onsubmit = "checkValue()". And then in my JS file, I would just include checkValue(form) as its parameter. If i want to do a check after every single button is pressed, I am not sure how to do this or what to pass in as its parameter.
Simple mock up hopefully to get you one your way.
Fiddle: http://jsfiddle.net/AtheistP3ace/krr3tgLx/1/
HTML:
<form method="post">
<div id="f1" style="display: block;">
<div class="label">Value 1:</div>
<input type="text" name="name" />
<button id="next1" type="button" onclick="checkValue(this)">Next</button>
</div>
<div id="f2">
<div class="label">Value 2:</div>
<br>
<input type="text" name="name" />
<button type="button" onclick="checkValue(this)">Next</button>
<br>
</div>
<div id="f3">
<div class="label">Value 3:</div>
<br>
<input type="text" name="name" />
<button type="button" onclick="checkValue(this)">Next</button>
<br>
</div>
</div>
</form>
JS:
function checkValue (button) {
// Finds the sibling input of the button
var input = $(button).siblings('input');
// Gets input value
var value = input.val();
// Stops showing next div if no value
if (value == '') {
return false;
}
else {
// Finds the parent div holding button and input
var div = $(button).closest('div');
// Fades out current div
div.fadeOut();
// Gets next div and fades it in
div.next().fadeIn();
}
}
CSS:
form > div {
display: none;
}
From my assumptions this is what you are looking for :
Multipart form handler
Basically I wired up each button with a class
<button id = "next1" type="button" class="check-btn">Next</button>
Then I used Jquery to get all those buttons and find the parent div (based on your structure) and then get all the child inputs (can include selects etc). From here you can continue to tweak to perform a check on each type of input etc.
$(document).ready(function(){
$('.check-btn').on('click',function(){
var parent = $(this).parent('div');
var elems = parent.find('input');
alert(elems.length);
//DO checks here for each element
});
});
I am trying to set-up the multi steps form validation using the Parsely.js validation plugin.
I followed the documentation here: "http://parsleyjs.org/doc/examples/multisteps.html" - but the only problem is I am going to have few forms that will have multi steps across the site and on some pages there will be more than one.
The snippet provided only support one form at a time, I need to specify an ID for each form as showed below:
<script type="text/javascript">
$(document).ready(function () {
$('.next').on('click', function () {
var current = $(this).data('currentBlock'),
next = $(this).data('nextBlock');
// only validate going forward. If current group is invalid, do not go further
// .parsley().validate() returns validation result AND show errors
if (next > current)
if (false === $('#demo-form').parsley().validate('block' + current))
return;
// validation was ok. We can go on next step.
$('.block' + current)
.removeClass('show')
.addClass('hidden');
$('.block' + next)
.removeClass('hidden')
.addClass('show');
});
});
</script>
Is there a way to tweak the snippet so it automatically detect if the form has more than one step and apply the appropriate behavior/settings accordingly? Rather than having to duplicate that snippet over and over for each form.
Here is how the HTML would look like:
<form id="demo-form" data-parsley-validate>
<div class="first block1 show">
<label for="firstname">Firstname:</label>
<input type="text" name="firstname" data-parsley-group="block1" required/>
<label for="lastname">Lastname:</label>
<input type="text" name="lastname" data-parsley-group="block1" required />
<span class="next btn btn-info pull-right" data-current-block="1" data-next-block="2">Next ></span>
</div>
<div class="second block2 hidden">
<label for="fullname">Email:</label>
<input type="text" name="fullname" required data-parsley-type="email" data-parsley-group="block2" />
<span class="next btn btn-info pull-left" data-current-block="2" data-next-block="1">< Previous</span>
<input type="submit" class="btn btn-default pull-right" />
</div>
</form>
You need to change the code to specify the form the user is currently working with. I've altered the code block you're using to do that, comments included:
$(document).ready(function () {
$('.next').on('click', function () {
// Find the form whose button was just clicked
var currentForm = $(this).parents('form').first();
var current = $(this).data('currentBlock'),
next = $(this).data('nextBlock');
// only validate going forward. If current group is invalid, do not go further
// .parsley().validate() returns validation result AND show errors
if (next > current)
// Use currentForm found above here, rather than hard coded form id
if (false === currentForm.parsley().validate('block' + current))
return;
// validation was ok. We can go on next step.
// Hide current block on current form
currentForm.find('.block' + current)
.removeClass('show')
.addClass('hidden');
// Show next block on current form
currentForm.find('.block' + next)
.removeClass('hidden')
.addClass('show');
});
});
Hi all I have the following code as seen below whch adds a new row consisting of a text field and radio button, I have written the JS to add a new row, and I use a .find() to append the new input field with a blank value. I am new to JS and want to perform another .find() when cloning to add a value to the radio input, could someone show me how to do so please.
<div id='1'>
<div class="template">
<div>
<label class="right inline">Response:</label>
</div>
<div>
<input type="text" name="responseText[]" value="" maxlength="400" />
</div>
<div>
<input type="radio" name="responseRadio[]" value="" />
</div>
</div>
<div>
<input type="button" name="addNewRow" value="Add Row" />
</div>
</div>
JS to add new row:
var $template = $('.template');
$('input[type=button]').click(function() {
$template.clone().insertAfter($template).find("input:text").val("");
});
Just get the cloned template and use any method you like on it before inserting it back:
var $template = $('.template');
$('input[type=button]').click(function() {
var $elem = $template.clone();
$elem.find("input:text").val("");
$elem.find("input:radio").val("whatever");
$elem.insertAfter($template);
});
Here's a fiddle: http://jsfiddle.net/SWCPD/1/
You can try like this -
var $clone = $template.clone();
$clone.find("input:text").val("");
$template.after($clone);
var $clonedNode = $template.clone();
$clonedNode.find('input:text').val('');
$clonedNode.find('input:radio').attr('checked', 'checked');
$template.insertAfter($clonedNode);
is to set the radiobutton to checked.