I have the following form fields:
<div id="filename-url-container">
<div class="form-inline form-group">
<input name="filename[]" class="form-control" placeholder="Filename" type="text">
<div class="input-group">
<input name="url[]" class="form-control" placeholder="URL" type="text">
<span class="input-group-btn">
<button class="btn btn-default btn-add" type="button">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
</div>
</div>
I want to grab the first child each time the button is pressed and append it to the bottom of the filename-url-container div without the values of the original cloned fields.
I tried to get this to work but it's not appending correctly:
$('#filename-url-container').on('click', '.btn-add', function (e) {
e.preventDefault();
var formGroup= $('#filename-url-container :first-child');
$('#filename-url-container').append(formGroup);
console.log(controlForm);
});
You should .clone the elements before appending them - as written your code would simply take the existing elements and try to move them to exactly the same place.
You also need to constrain your selector, else it will pick every :first-child element within the container, not just the one that's the immediate child:
$('#filename-url-container').on('click', '.btn-add', function (e) {
var formGroup= $('#filename-url-container > :first-child').clone(true);
formGroup.find('input').val(''); // erase values
$('#filename-url-container').append(formGroup);
});
demo at http://jsfiddle.net/alnitak/dvqgnga0/
$('#filename-url-container').on('click', '.btn-add', function (e) {
e.preventDefault();
var formGroup= $('#filename-url-container div:first-child').html();
$('#filename-url-container').append(formGroup);
console.log(formGroup);
});
You need to append html, not object it self.
http://jsfiddle.net/npdh2v3L/
I don't think you are using :first-child correctly. :first-child refers to the first child of the type to it's left. Other than that you just need to get rid of those values. Additionally, I'm not seeing a need to Event.preventDefault() since you are not using a submit button.
$('#filename-url-container .btn-add').click(function(){
var clone = $('#filename-url-container .form-group:first-child').clone(true);
clone.find('input').val('');
$('#filename-url-container').append(clone);
});
Related
html code:
<button id="add"></button>
<div id="count_search">
<span class="total_count">Total: <span id="record_count"></span></span></span>
<input type="text" class="txtbox search" placeholder="Search" id="search">
</div>
Jquery code:
$("#add").click(function(){
$("#count_search").empty();
})
I want to show count_search div once again on clicking on any other button execpt to add button
In above code add is button on which empty() is implimented. On clicking on add button count_search is got hide. Then after I want to restore that div content
.empty() deletes the elements in your container (count_search).
Instead, you can use .hide()/.show() or better approach, you can use .toggle() that show or hide your element.
$("#add2").click(function() {
$("#count_search").toggle();
});
$("#add").click(function() {
if ($("#count_search").is(":visible")) {
$("#count_search").hide();
} else {
$("#count_search").show();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add">Show/Hide</button>
<button id="add2">Toggle</button>
<div id="count_search">
<span class="total_count">Total: <span id="record_count"></span></span></span>
<input type="text" class="txtbox search" placeholder="Search" id="search">
</div>
By empty() you are deleting an item in DOM.
Instead of empty, you can use toggle(), which hides the element and If you click once again, the item will show.
$("#add").click(function(){
$("#count_search").hide();
})
I want to append a duplicate of an input box in a parent box. Here is my HTML structure:
<div class="reading-group input-group">
<input type="text" placeholder="Enter Reading link" id="link">
</div>
+ Add another link
And here is my jQuery code:
function addPlaceholder(parentClass){
var placeHolder = $(parentClass).children().eq(0);
$(parentClass).append(placeHolder);
console.log(placeHolder);
}
$('.add-reading-btn').click(function(){
addPlaceholder('.reading-group');
});
Here is the jsfiddle link: https://jsfiddle.net/abhishekraj007/kexe6gxn/
What am I doing wrong?
Your code is taking the existing <input> element and moving it from the <div> and back into the <div>, so it looks like nothing is happening. If you .clone() the element and then .append() it, a new element will be added.
Here is a working example:
function addPlaceholder(parentClass) {
var placeHolder = $(parentClass).children().eq(0).clone();
$(parentClass).append(placeHolder);
console.log(placeHolder);
}
$('.add-reading-btn').click(function() {
addPlaceholder('.reading-group');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="reading-group input-group">
<input type="text" placeholder="Enter Reading link" id="link">
</div>
+ Add another link
If you want to add focus to your <input> element on load, you can do so by adding this line to the bottom of your code:
$('#link').focus();
If you want to add focus to the new element on creation, as well as give it an empty value rather than copying the prior element's value, add this line to the end of your addPlaceholder() function:
$(placeHolder).val("").focus();
you can just add the .clone() method of jquery to create a clone of the textbox like below . You were only referring to the same element not the cloned html before.
$(document).ready(function(){
function addPlaceholder(parentClass){
var placeHolder = $(parentClass).children().eq(0).clone();
$(parentClass).append(placeHolder);
//console.log(placeHolder);
}
$('.add-reading-btn').click(function(){
addPlaceholder('.reading-group');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="reading-group input-group">
<input type="text" placeholder="Enter Reading link" id="link">
</div>
+ Add another link
Here is a working fiddle
https://jsfiddle.net/kexe6gxn/2/
How to detect which dynamic button is clicked?
Note: The #dCalc Element is added dynamically...
<!-- STATIC -->
<div id="dBlock">
<!-- ADDED DYNAMICALLY -->
<div id="dCalc">
<input id="firstNumber" type="text" maxlength="3" />
<input id="secondNumber" type="text" maxlength="3" />
<input id="btn1" type="button" value="Add" />
<input id="btn2" type="button" value="Subtract" />
<input id="btn3" type="button" value="Multiply" />
<input id="btn4" type="button" value="Divide" />
</div>
</div>
$("input").click(function(e){
var idClicked = e.target.id;
});
$(function() {
$('input[type="button"]').click(function() { alert('You clicked button with ID:' + this.id); });
});
Since the block is added dynamically you could try:
jQuery( document).delegate( "#dCalc input[type='button']", "click",
function(e){
var inputId = this.id;
console.log( inputId );
}
);
demo http://jsfiddle.net/yDNWc/
jQuery can be bound to an individual input/button, or to all of the buttons in your form. Once a button is clicked, it will return the object of that button clicked. From there you can check attributes such as value...
$('#dCalc input[type="button"]').click(function(e) {
// 'this' Returns the button clicked:
// <input id="btn1" type="button" value="Add">
// You can bling this to get the jQuery object of the button clicked
// e.g.: $(this).attr('id'); to get the ID: #btn1
console.log(this);
// Returns the click event object of the button clicked.
console.log(e);
});
Detect event on dynamically created elements
Two examples, jQuery and vanilla JavaScript ahead:
jQuery
Use the .on() method with delegated events, which follows this syntax:
$("staticParentSelector").on("eventName", "dynamicChildSelector", handlerFn);
Example:
// Assign event listeners to dynamic child elements
// Will work for either existent elements or inserted in the future
$("#dBlock").on("click", '[type="button"]', (evt) => {
const staticParent = evt.delegateTarget; // This is #dBlock
const dynamicChild = evt.currentTarget; // This is the dynamic child
console.log(`Static Parent ID is: ${staticParent.id}`)
console.log(`Dynamic child ID is: ${dynamicChild.id}`)
});
<!-- STATIC -->
<div id="dBlock">
<!-- ADDED DYNAMICALLY -->
<div id="dCalc">
<button type="button" id="btn1">Add</button>
<button type="button" id="btn2">Subtract</button>
<button type="button" id="btn3">Multiply</button>
<button type="button" id="btn4">Divide</button>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
JavaScript
The same in vanilla JavaScript can be achieved like the following, with the difference in that JS has no notion of delegateTarget (which is a jQuery property on their proprietary Event object) therefore the slight modification:
// Assign event listeners to dynamic child elements
// Will work for either existent elements or inserted in the future
document.querySelector("#dBlock").addEventListener("click", (evt) => {
const staticParent = evt.currentTarget; // This is #dBlock
const dynamicChild = evt.target.closest('[type="button"]'); // This is the dynamic child
if (!dynamicChild) return; // Do nothing (no designated dynamic child is clicked)
console.log(`Static Parent ID is: ${staticParent.id}`)
console.log(`Dynamic child ID is: ${dynamicChild.id}`)
});
<!-- STATIC -->
<div id="dBlock">
<!-- ADDED DYNAMICALLY -->
<div id="dCalc">
<button type="button" id="btn1">Add</button>
<button type="button" id="btn2">Subtract</button>
<button type="button" id="btn3">Multiply</button>
<button type="button" id="btn4">Divide</button>
</div>
</div>
as you can see neither of the above implementations stick solely on the Event.target Element per-se, for the reason that if we had i.e. an icon inside the buttons (like: <button id="add" type="button">Add <i class="icon-plus"></i></button>) and if a click landed on the icon directly, the Event.target would end up being the icon, not the Button Element - and we might miss to retrieve the needed data, like the specific button ID etc, resulting in a broken app logic.
I have an instance where my datepickers won't work by button click, so I figure find the closest input and .click() or .focus() (for it's datepicker, since the same field is to be affected). For the sake of this demo, from the button/icon click - find the closest input and focus/click on it. If correct, the border will glow blue. http://jsfiddle.net/81tvr0op/
HTML
<table>
<tr>
<th>
<div class="input-group date">
<input type="text" />
<span class="input-group-btn">
<button class="btn default" type="button">
<i class="fa fa-calendar"></i>
Icon
</button>
</span>
</div>
</th>
</tr>
</table>
jQuery
...something like
$(".date > span > button").on('click', function (e) {
e.preventDefault();
$(this).closest("th").find("input:text").click();
});
...right?
If I understand correctly, you are trying to place the cursor into the input box when the user clicks the button.
To do that, you should use .focus() instead of .click().
Working example:
http://jsfiddle.net/81tvr0op/1/
From your jsfiddle, something like this should work.
$("button").on('click', function (e) {
e.preventDefault();
$(this).parent().siblings(0).focus();
});
Or, give your input an id and do something like:
$("button").on('click', function (e) {
e.preventDefault();
$("#dateInput").focus();
});
How to clear all input fields in a Bootstrap V3 modal when clicking the data-dismiss button?
http://getbootstrap.com/javascript/#modals shows an event for when a modal is hidden. Just tap into that:
$('#modal1').on('hidden.bs.modal', function (e) {
$(this)
.find("input,textarea,select")
.val('')
.end()
.find("input[type=checkbox], input[type=radio]")
.prop("checked", "")
.end();
})
http://jsfiddle.net/5LCSU/
I would suggest the above as it bind the clearing to the modal itself instead of the close button, but I realize this does not address your specific question. You could use the same clearing logic bound to the dismiss buttons:
$('[data-dismiss=modal]').on('click', function (e) {
var $t = $(this),
target = $t[0].href || $t.data("target") || $t.parents('.modal') || [];
$(target)
.find("input,textarea,select")
.val('')
.end()
.find("input[type=checkbox], input[type=radio]")
.prop("checked", "")
.end();
})
http://jsfiddle.net/jFyH2/
There is a more easy and beautiful way:
$('#MyModal').on('hidden.bs.modal', function () {
$(this).find('form').trigger('reset');
})
reset is dom build-in funtion, you can also use $(this).find('form')[0].reset();
And Bootstrap's modal class exposes a few events for hooking into modal functionality, detail at here.
hide.bs.modal This event is fired immediately when the hide instance
method has been called.
hidden.bs.modal This event is fired when the modal has finished being
hidden from the user (will wait for CSS transitions to complete).
If you are using a form in the modal then you can use
$("#form_id").trigger("reset");
I did it in the following way.
Give your form element (which is placed inside the modal) anID.
Assign your data-dimiss an ID.
Call the onclick method when data-dimiss is being clicked.
Use the trigger() function on the form element.
I am adding the code example with it.
$(document).ready(function()
{
$('#mod_cls').on('click', function () {
$('#Q_A').trigger("reset");
console.log($('#Q_A'));
})
});
<div class="modal fade " id="myModal2" role="dialog" >
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" ID="mod_cls" data-dismiss="modal">×</button>
<h4 class="modal-title" >Ask a Question</h4>
</div>
<div class="modal-body">
<form role="form" action="" id="Q_A" method="POST">
<div class="form-group">
<label for="Question"></label>
<input type="text" class="form-control" id="question" name="question">
</div>
<div class="form-group">
<label for="sub_name">Subject*</label>
<input type="text" class="form-control" id="sub_name" NAME="sub_name">
</div>
<div class="form-group">
<label for="chapter_name">Chapter*</label>
<input type="text" class="form-control" id="chapter_name" NAME="chapter_name">
</div>
<button type="submit" class="btn btn-default btn-success btn-block"> Post</button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button><!--initially the visibility of "upload another note" is hidden ,but it becomes visible as soon as one note is uploaded-->
</div>
</div>
</div>
</div>
Hope this will help others as I was struggling with it since a long time.
Put the contents in your modal inside a form and give it an ID which is equal to "myForm".
When the close button is clicked, give an onclick to the function "myFunction()".
<button class="btn btn-default" data-dismiss="modal" onclick="myFunction()">Cancel</button>
function myFunction() {
document.getElementById("myForm").reset();
}
$('[data-dismiss=modal]').on('click', function (e)
{
var $t = $(this),
target = $t[0].href || $t.data("target") || $t.parents('#myModal') || [];
$(target)
.find("input")
.val('')
.end()
.find("input[type=checkbox]")
.prop("checked", " ")
.end();
$("span.inerror").html(' ');
$("span.inerror").removeClass("inerror");
document.getElementById("errorDiv1").innerHTML=" ";
})
This code can be used on close(data-dismiss)of modal.(to clear all fields)
Here I have cleared my input fields and my div as id="errorDiv1" which holds all validation errors.
With this code I can also clear other validation errors having class as inerror which is specified in span tag with class inerror
and which was not possible using document.getElementsByClassName
This is helpfull, its work for me..
$('.bd-example-modal-sm').on('hidden.bs.modal', function () {
$(this).find("select").val('').end(); // Clear dropdown content
$("ul").empty(); // Clear li content
});
The following worked for me:
$(':input').val('');
However, it is submitting the form, so it might not be what you are looking for.
In addition to #Malk, I wanted to clear all fields in the popup, except the hidden fields.
To do that just use this:
$('.modal').on('hidden.bs.modal', function () {
$(this)
.find("input:not([type=hidden]),textarea,select")
.val('')
.end()
.find("input[type=checkbox], input[type=radio]")
.prop("checked", "")
.end();
});
This will clear all fields, except the hidden ones.
enclose your modal body inside a form with an id="myform"
and then
$("#activatesimModal").on("hidden.bs.modal",function(){
myform.reset();
});
should do the trick