JQuery Append Html onclick function - javascript

Im trying to remove the text box evenly. I mean for each textbox i want the remove button.If i click the remove button i want to delete the textbox
Html for adding multiple text box
<pre><div id="TextBoxDiv1">
<label style="float: none;"> Bus Model
<input style="width: 150px;" type="text" value="" class="validate[required,custom[onlyNumberSp]]" name="numsValid" id="numsValid">
<img src="images/india_rupess.png" style="margin-left:18px;"> :</label>
<input style="width: 150px;" type="text" value="" class="validate[required,custom[onlyNumberSp]]" name="numsValid" id="numsValid">
<label style="float: none;margin-left: 16px;"><span class="font-dollar">﹩</span> :</label>
<input style="width: 150px;" type="text" value="" class="validate[required,custom[onlyNumberSp]]" name="numsValid" id="numsValid">
Add Remove
</div></pre>
This is my script
<pre>var counter = 2;
$("#addButton").click(function () {
$("#TextBoxesGroup").append('<div id="TextBoxDiv' + counter + '" class="textadd""><label style="float: none;"> Bus Model <input style="width: 150px;margin-left:3px;" type="text" value="" class="validate[required,custom[onlyNumberSp]]" name="bus' + counter + '" id="numsValid"><img src="images/india_rupess.png" style="margin-left:21px;"> :</label><input style="width: 150px;margin-left:3px;" type="text" value="" class="validate[required,custom[onlyNumberSp]]" name="rs' + counter + '" id="numsValid"><label style="float: none;margin-left: 19px;"><span class="font-dollar">﹩</span> :</label><input style="width: 150px;margin-left:2px;" type="text" value="" class="validate[required,custom[onlyNumberSp]]" name="dollar' + counter + '" id="numsValid"> <a href="javascript:;" onClick="javascript:alert("test");" >Remove</a></div>');
counter++;;
});
Click to view http://jsfiddle.net/b8DRT/

You may add a class on your delete button and use .on() on your $("#TextBoxesGroup")
to add the remove event. Like this
$("#TextBoxesGroup").on('click', '.removeButton', function(){
$(this).closest('div').remove();
});
And here's the updated fiddle..

id is unique for an HTML element in complete document. You are giving same id to multiple elements. Secondly when you attach event handlers using click, they are bound to elements that are already present in the DOM and not the ones which are to be added later. If you want to attach click event handlers you should use the on method like below:
$(document).on('click', '.removeButton', function(e){
// your logic here...
});

Related

Fill input with max value on click

I'm currently trying to find a way to fill the max value of an input according to the
max="#value"
Currently I'm using asp.net mvc, I'm getting data from a datatable and I render this information inside a html table where in my tr> /tr> I have a td> /td> that looks like this
<td align="center"><input type="number" name="txtID" class="txtID" oninput="setValueAttr(this)" min="0" max="#monto.Trim()" value="" step="any" style="width: 100px" /></td>1
Can anyone tell me how to make a javascript function that automatically fills the max="" value inside a Html TableRow?
The problem is that each row has its unique max #value
Assume the following HTML:
<td align="center">
<input type="number" name="txtID" class="txtID" oninput="setValueAttr(this)" min="0" max="#monto.Trim()" value="" step="any" style="width: 100px" />
<button class="set-max">Max value</button>
</td>
You can add an event listener on the button via JavaScript e.g. put this code in the bottom of your table or in the bottom of the <body> tag.
<script>
var buttons = document.querySelectorAll('.set-max');
buttons.forEach(function (button) {
button.addEventListener('click', function (event) {
var input = event.currentTarget.parentElement.querySelector('input[type="number"]');
input.value = input.max;
});
};
<script>
If the button ends up somewhere else you'd need to adjust the event listener to find the actual target element by navigating through the DOM hierarchy

how to generate the id of a div dynamically using javascript

I have a (+) sign and a (-) sign. If the user clicks on the + sign than whatever their in the row will automatically get generated the same with new id.
Now when user click on + sign than div id and text box under it will get changed.
Code below for div as follows:
<div class="row" id="Div0">
<div class="col-md-3">
<div class="form-group">
<label for="name">Last Name</label>
<input type="text" class="form-control" id="txtLastName0" placeholder="Enter name" required="required" />
</div>
</div>
<div class="col-md-9"></div>
</div>
Now when user clicks on + sign the new row with text box with new id txtLastName1 will get generated.
Now on click of + sign how do i get new id of textbox and a div with new row.
Div1 and textbox1 will get generated
Basically what you should do is, keep the markup you want to generate as a template in your DOM and when user clicks the "Add" button, clone this markup and append to the DOM (to a container div). then update the Id's of the input and divs as needed.
A simply sample would be like
<div class="row" id="template" style="display: none;">
<div class="col-md-3">
<div class="form-group">
<label for="name">Last Name</label>
<input type="text" class="form-control lname" id="txtLastName"
placeholder="Enter name" required="required" />
</div>
</div>
<div class="col-md-9"></div>
</div>
<button id="btnAdd">+</button>
<div id="container"></div>
Now wire up a click event handler to the Add/+ button. You may use the jQuery clone() method.
$(function () {
$("#btnAdd").click(function(e) {
e.preventDefault();
var childCount = $("#container").children().length;
var c = $("#template").clone().show();
c.attr("id", "Div" + childCount );
c.find(".lname").attr('id', 'txtLastName' + childCount);
$("#container").append(c);
});
});
For deleting, you can add a event handler on the delete button and remove the specific div from dom. jQuery remove() method will do it. Use closest() and find as needed to get the correct div to remove.
Here is a working simple jsbin sample for your reference

id + 1 on append, responsive filemanager multiple select image

still looking for code, how can i have different id on input attribute each time i click add button, I have no idea on how to make the id unique ,please help me..
$(document).ready(function(){
$("#btn2").click(function(e){
e.preventDefault();
var id = $(".inputclass").attr("id");
var newid = parseInt(id) + 1;
$('.inputclass').attr("id", ""+newid+"");
$("#gallery").append(
'<div class="added">'
+'<div class="col-md-2">'
+'<div>'
+'<a class="fileman" href="#"" data-toggle="modal" data-target="#FileManager">'
+'<img id="1" class="imageview center-block" src="/assets/img/noimage150x150.png"></a>'
+'</div>'
+'<a class="tutup btn btn-sm btn-warning">delete<a>'
+'<input class="inputclass" name="image" type="text" value="" class="form-control" id="1"/>'
+'</div>'
+'</div>'
);
});
$("#gallery").on('click', '.tutup', function(e) {
e.preventDefault();
$(this).parent().remove();
});
});
Here you go. You just need to insert id when you generate html
+'<input class="otherClass" name="image" type="text" value="" class="form-control" id="'+newid+'"/>'
Also you need to change class name of input.
https://jsbin.com/pinegowotu/1/edit?html,console,output
Fix bin
Hope this helps.

replace a <p> element with an input element

I have a p element which I want to replace with an input element when user clicks on it. The might not be present during page load so I use delegate to catch the click event.
html(after <p> was loaded)
<div class="phrases">
<div class="predefined-phrase>
<p id="1">A predefined phrase"</p>
</div>
</div>
I want it to be like this
<div class="phrases">
<div class="predefined-phrase">
<input type="text" id="1" class="form-control input-sm" value="A predefined phrase">
</div>
</div>
My js file has the following code:
$(".phrases").on('click', ".predefined-phrase", function (event){
event.preventDefault();
var phrase = $(this).children().text();
var id = $(this).children().attr('id');
var input = '<input type="text" class="form-control input-sm" id="'+id+'" value="'+phrase+'">';
$(this).children().remove();
$(this).append(input);
});
<p> is replaced normally by input but i cannot type anything. I can only type if left click is pressed on input box continiously. I also want to catch a keypress event on the new input so to edit or to delete the specific phrase. But I cannot even type on the input box. Why is this happening? Can i normally catch the keypress event after I have appended the input (and works as it should) inside the click event callback? The point is that after user presses the phrase is edited with ajax and the input box dissappears and p is loaded back with the new edited phrase or fully deleted.
$(function(){
$('.predefined-phrase p').click(function() {
var id = $(this).attr('id');
var phrase = $(this).text();
var newInput="<input type='text' id='"+id+"' value='"+phrase+"' />";
$(this).replaceWith(newInput);
});
});
DEMO FIDDLE
Just check the target. If it is a input, do nothing :
$(".phrases").on('click', ".predefined-phrase", function (event){
if($(event.target).is('input')) return;
event.preventDefault();
var phrase = $(this).children().text();
var id = $(this).children().attr('id');
var input = '<input type="text" class="form-control input-sm" id="'+id+'" value="'+phrase+'">';
$(this).children().remove();
$(this).append(input);
});
Well, this is a native JS solution, but hopefully it will point you in the right direction, or if you an use it instead of jQuery, that works too. Not that I've changed your ID to not start with a number, as mentioned by C-link, as that is not allowed.
document.getElementById("n1").addEventListener("click", function filler(){
this.outerHTML = '<input type="text" id="' + this.id + '" class="form-control input-sm" value="' + this.innerHTML + '" />
this.removeEventListener("click" filler)'
});
I would suggest the next changes:
<div class="predefined-phrase">
<input type="text" data-id="1" class="form-control input-sm" value="A predefined phrase">
</div>
jQuery script:
$('.predefined-phrase').click(function() {
var id = $('p', this).attr('data-id');
var value = $('p', this).text();
$('p', this).replaceWith('<input type="text" data-id="' + id + '" class="form-control input-sm" value="' + value + '" />')
});
First of all, don't use id starting from number.
And for your solution you can use replaceWith method like below:
$('#your_id').replaceWith('<input type="text" id="your_id" class="form-control input-sm" value="A predefined phrase" />');

Dynamically remove a dynamically added input (type=file)

I have a form where user can add files to be uploaded. Change event on that input adds new input the same type and so on. But the new inputs have to have "X" character with click event attached to it to be able to remove the input field and the X chracter.
The form:
<form id="upload_form">
<div class="p_file">
<p class="icon">X</p>
<input type="file" name="userfile1" size="40" class="required" />
</div>
</form>
and the JavaScript:
$('#upload_form input[type="file"]').change(function(){
addUploadField($(this));
});
function addUploadField($field)
{
$current_count = $('#upload_form input[type="file"]').length
$next_count = $current_count + 1;
$field.parent('p').after('
<div class="p_file" >
<p class="icon">X</p>
<input type="file" name="userfile'+$next_count+'" size="40" />
</div>
');
$field.unbind('change');
$nextField = $('#upload_form input[type="file"]').last();
$nextField.bind('change',function(){
addUploadField($(this));
});
$("#upload_form .icon").on('click',function(){
removeUploadField($field);
});
}
function removeUploadField($field)
{
$field.parent('p').remove();
}
The code above remove all the fields after the clicked 'X' character. What I want to do is to remove only the next input field.
I tried to prepare this example in jsFiddle, but I can't make this work. Anyhow maybe this would help.
Putting "div" tag inside "p" tag is the main problem
Remove is corrected in this code
Note: In your html code "div" is is added inside "p" tag, this is invalid practice
HTML:
<form id="upload_form">
<div class="p_file">
<div class="icon">X</div>
<input type="file" name="userfile1" size="40" class="required" />
</div>
</form>
Script:
$('body')
.delegate('#upload_form input[type="file"]', 'change', inputChanged)
.delegate('#upload_form .icon', 'click', removeField);
function inputChanged() {
$current_count = $('#upload_form input[type="file"]').length;
$next_count = $current_count + 1;
$(this).closest('.p_file').after(
'<div class="p_file" ><div class="icon">X</div>' +
'<input type="file" name="userfile'
+ $next_count + '" size="40" /></div>');
}
function removeField(){
$(this).closest('.p_file').remove();
return false;
}
Link: http://jsfiddle.net/cBrQX/2/

Categories