Append input value to a div - javascript

can someone show me how to take an input value and append it to a div once the user clicks on an Add link?
This is the best I could do.
HTML:
<div id="customUtility-container"></div>
Add
jQuery:
$(function() {
var addDiv = $('#customUtility-container');
var i = $('#customUtility-container').size() + 1;
$('#addUtility').live('click', function() {
$('#customUtility').val().appendTo(addDiv);
$('<p><label for="customUtility-container"><input type="text" id="customUtility" size="20" name="customUtility_' + i +'" value="" placeholder="" /></label> Remove</p>').appendTo(addDiv);
i++;
return false;
});
$('#removeUtility').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
This creates another input field however; I just want to have one input box, have the user click Add, then it takes that value, puts it into the list, and clears the input box so the user can add something else again.

Use jQuery's append() function
addDiv.append($('#customUtility').val());
Here's a working fiddle.
Warning: opinion below
When creating a variable to store a jQuery object, I think it's helpful to prefix the variable with $. This way, you know that you're working with a jQuery object. It also makes it easier for those coming behind you to recognize what you're doing:
var $addDiv = $('#customUtility-container');
$addDiv.append($('#customUtility').val());

Something like:
addDiv.html(addDiv.html() + whateveryouwanttoadd)

addDiv.append($('#customUtility').val());

Change
$('#customUtility').val().appendTo(addDiv);
To
addDiv.append($('#customUtility').val());
val() method gives the value of the input element and you cannot call a jQuery method on a string which will throw an error.
Working demo - http://jsfiddle.net/t9D8R/

I ended up scrapping everything and redoing it:
$(function() {
var i = $('#customUtility-container').size() + 1;
$("#addUtility").on("click", function() {
$("#customUtility-container").append('<div id ="customUtility_' + i +' " name="customUtility_' + i +' ">'+ $("#customUtility").val() + 'Remove</div>');
});
$('#removeUtility').live('click', function() { $(this).closest('div').remove();
i--;
});
});

Related

jquery function to handle a series of href in div rows

Imagine a table (actually constructed of divs) with rows and in the final cell in each row, I have an input text and a link that look like this:
<input type="text" name="message" id="message_#Model.IncidentId" value="">
Send a Comment
After each row (the parent div), I have a chunk of code like the following to ajaxify the link and text input:
$('#send_#Model.IncidentId').click(function () {
var msg = $('#message_#Model.IncidentId').val();
if (msg != '') { $(this).attr('href', this.href + '?msg=' + msg) }
$.post(this.href, function (json) {
if (json.jsonResult === null) {
$("#msg_#Model.IncidentId").html("Sent...");
} else {
window.location.href = json.jsonResult;
}
});
return false;
});
It works. However, there are at least 10 of these on each page. What I'm trying to do is consolidate the jquery into one function to handle all the links. Can I use jquery "this" or pass the IncidentId to the jquery function or something? It seems like "this" would not work because the input text is outside of the link? How can I do this to have one function for the entire page?
Keep in mind it's not imperative that I splash everything with the IncidentId. So, if I need to make one or more of the ids or names generic, that would be ok. It just needs to not get confused about what pair it's handling. I've seen some comments that a form might help, but 10+ forms on a page is ok? Plus, as it stands, there will never be any other input fields than what is shown above.
I appreciate your help. Thanks.
Update: So, I basically used Søren's recommended html5 data-* (data-id) attribute in my link, gave it a class name, and then moved my url down to the function as well...and then simply replaced all my #Model.IncidentIds. The one catch is that I had to use the following to register my click event:
$(document).on('click', ".ajax-link", function () {
I guess because I'm using handlebars to dynamically generate the page? I hadn't tested the original function since I moved it to my infinite scroll layout mentioned in the comments. Thanks all for replying.
Try this:
<input type="text" name="message" data-input-id="1" value="">
<a class="ajax-link" href="#" data-link-id="1">Send a Comment</a>
$('.ajax-link').click(function () {
var id = $(this).attr('data-link-id');
var msg = $('[data-link-id='+id+']').val();
if (msg != '') { $(this).attr('href', this.href + '?msg=' + msg) }
$.post(this.href, function (json) {
if (json.jsonResult === null) {
$("[data-link-id='+id+']").html("Sent...");
} else {
console.debug(json.jsonResult);
}
});
return false;
});
Make sure the link and field have the same id
First, make sure you have some useful class name's in place. E.g.,
<input type="text" class="incident-message" name="message" id="message_#Model.IncidentId" value="">
Send a Comment
That should allow you to create a nice, row-generic script like this:
$('.incident-link').click(function(e) {
e.preventDefault();
var $this = $(this),
$row = $this.closest('div'),
$msg = $row.find('.incident-message');
var msg = $msg.val();
if (msg != '') {
$this.attr('href', $this.attr('href') + '?msg=' + msg);
}
$.post($this.attr('href'), function (json) {
if (json.jsonResult === null) {
// I didn't see any markup for your #msg element, but assuming
// that you give it a useful classname, you can do something
// similar to this:
$row.find('.some-msg-className').html('Sent...');
} else {
window.location.href = json.jsonResult;
}
});
});
As far as grouping the events to a single handler, just use a class instead of id's.
$('.thisKind').click(function () {
or if the content is dynamic, use a single event for the parent with a selector in the on() method
$('#parentId').on("click", ".thisKind", function() {
As far as the this usage, you should familiarize yourself with jquery's DOM traversal using closest() to go up the tree and find() to go down

append value to an input field in JQuery

I have an input type="tel" with id="#enter" and I want to add append values from button clicks. I have done this:
$("#one").click(function () {
$("#myInput").val("1");
});
$("#two").click(function () {
$("#myInput").val("2");
});
So every time a button is pressed from #id 1-9 it enters the corresponding numeric value.
However this doesn't append the value in the input field type just replaces the existing value with the value of the button clicked. How can it append the values?
This is the JSFiddle
You can use something like this to append values:
$("#myInput").val(function() {
return this.value + '1';
});
You can also improve your approach by giving each number button a class and register the same event listener for all buttons. For example:
$(".dial").click(function () {
var number = $(this).data('number');
$("#myInput").val(function() {
return this.value + number;
});
});
Where the button would be defined as
<button type="button" class="btn btn-primary btn-xs1 dial" data-number="4"> <b>GHI<br>4
as so on.
Demo: http://jsfiddle.net/8R9xL/2/
Try this
$("#one").click(function(){
$("#myInput").val($("#myInput").val()+"1");
});
Of course it doesn't append the value, you've done nothing to make it append the value.
To append the value you have to...append the value. Get the current value, add (append) something to it, and then set that.
$("#one").click(function(){
var input = $("#myInput");
input.val(input.val() + "1");
});
$("#two").click(function(){
var input = $("#myInput")
input.val(input.val() + "2");
});
$("#one").click(function(){
var input = $("#myInput");
input.val(parseInt(input.val() + 1));
});
$("#two").click(function(){
var input = $("#myInput")
input.val(parseInt(input.val() + 2));
});
I have done something like this.
$('.pin-number').on('click', (e) => {
$('#pin').val($('#pin').val() + e.target.innerText)
})
Where .pin-number is a set of divs containing a number from 0 to 9 (this is the reason that I use e.target.innerText instead of e.target.value), and #pin is the input where the values are inserted.
Hope this helps!

How can I add to the end of the string that already exists in input field?

Now, If I hit the button, it clears all in the input field, and it automatically inputs "#marry" to it.
But, I don't want it to be cleared:(
What if I want to add "#marry" to the end of the strings that already exists in the input field?
How can I customize my javascript part?
Input field
<textarea class="box text_area" cols="10" id="input" name="comment[body]"></textarea>
button
<a href="#topic" id="username" value="#marry”><span class='btn'>reply</span></a>
javascript
$(document).on('click', 'a#username', function() {
$(".box#input").val($(this).attr('value'));
}
val() has a callback with the arguments index and value, you can use that to easily add something to the value.
$(".box#input").val(function(_, val) {
return this.value + 'some extra string';
});
$(document).on('click', 'a#username', function() {
var self = this;
$(".box#input").val(function(_, val) {
return val + self.value;
});
});
First of all adeneo's answer is good and you should read it. Here is an alternative solution that does not use jQuery:
I assume that both these elements are a part of a form. Let's say for instance the form has an ID of "post". We can access it using document.forms and then its fields as such:
var input = document.forms.post["comment[body]"];
Now, we can add to its value whenever the button is clicked. First select username with getElementById or querySelector and then add the event:
username.addEventListener("click", function(ev){
input.value += ev.target.value;
});
Or with jQuery (this also delegates if the element is not in the DOM yet):
$(document).on('click', 'a#username', function() {
input.value += this.value;
});
It might be desirable to append an extra space between the current text and the username.
append #marry at the end of text area. you can use bellow code its working fine.
$(document).on('click', 'a#username', function () {
var txtvalue = $(".box#input").val();
$(".box#input").val(txtvalue + $(this).attr('value'));
});
see jsfiddle link http://jsfiddle.net/F6mkh/1/

jQuery .val() not setting the value of <select>

I would like to know why jQuery's .val() function is not setting the value of the <select> control for me after I called replaceWith, but it is working otherwise.
Please see here for a (not) working example.
<select><option>ABC</option><option>DEF</option></select>
<input type="button" onclick="ControlOff()" value="Turn Off Control" />
<input type="button" onclick="ControlOn()" value="Turn On Control" />
<input type="button" onclick="Test()" value="Value Setting Test" />
function ControlOff() {
$('select').each(function () {
$(this).replaceWith('<span class="select-type">' + $(this).val() + '</span>');
});
}
function ControlOn() {
$('.select-type').each(function () {
var selected = $(this).text();
$(this).replaceWith('<select><option>ABC</option><option>DEF</option></select>');
$(this).val(selected);
});
}
function Test() {
$('select').val('DEF');
}
The problem is, that $(this) in $(this).val(selected) refers to the removed <span> element, not your new element. You need to replace it with:
$('select').val(selected);
to grab the previously inserted new element.
Also, your code is unecessarily complex, this does the same thing, but simpler:
function ControlOn() {
$selectText = $('.select-type');
var selected = $selectText.text();
$selectText.replaceWith('<select><option>ABC</option><option>DEF</option></select>');
$('select').val(selected); // Use an id instead to match: #my-select-id
}
Make sure to give the <select> element an ID, otherwise it's going to mess up once you introduce a new <select> element somewhere else on the page.
See here for a working example.
The problem is that in ControlOn you have an each which is looping over .select-type elements which are span's and spans cannot be set with the val method:
You can fix this by changing the method to this:
function ControlOn() {
$('.select-type').each(function () {
var selected = $(this).text();
var $select = $('<select><option>ABC</option><option>DEF</option></select>');
$(this).replaceWith($select)
$select.val(selected);
});
}
Live example: http://jsfiddle.net/qSYYc/4/
set value of options will solve your problem. jsfiddle
<select><option value='ABC'>ABC</option><option value="DEF">DEF</option></select>
function ControlOn() {
$('.select-type').each(function () {
var selected = $(this).text();
$(this).replaceWith($('<select><option>ABC</option><option>DEF</option></select>').val(selected));
});
}
Rewrite your code like above, it would work!
The element referenced by this won't change to the select element you just created, it will always be the span element inside the scope of that function. Therefore you should set the value to the newly created select instead of the invariant $(this)!
I'd suggest you to use "disabled" attribute to turn select on and off, it, won't mess up the .val() functionality
function ControlOff() {
$("select").attr("disabled", "disabled");
}
function ControlOn() {
$("select").removeAttr("disabled");
}

How do I empty an input value with jQuery?

I’m trying to make a modal dialog with images where you can select multiple images. I need to get values from an input and then to empty it, but I cannot empty the input. I tried .val('') and .val(null), but neither worked for me.
Here is the full code:
$("#hdselect").click(function(){
$(".modal").html("");
$.post('mediaservice.php',{hd:'ok',images:$("#hdimages").val()},function(data){
$(".modal").append(data);
});
$(".modal").dialog({
'modal':true,
'title':"Click the image to select",
'width':960,
'height':600,
'resizable':false,
'show': {effect: 'drop', direction: "up"},
'buttons': {"Ok": function() {
var hd=Array();
var hdval=$("#hdimages").val();
$("#hdimages").attr('value',' ');
$("input[name='hd[]']:checked").each(function(){
hd.push($(this).val());
});
if(hdval!=''){
hdval=hdval+","+hd;
}else{
hdval=hd;
}
$("#hdimages").val(hdval);
var images=$("#hdimages").val();
$.post('mediaservice.php',{getHd:images},function(data){
$("#imgthumbBase").append(data);
});
$(this).dialog("close");
}
}
});
});
The idea is that the user clicks a button and a modal dialog opens with multiple images and checkboxes. At this point I need to get the values from an input, and then clear it.
To make values empty you can do the following:
$("#element").val('');
To get the selected value you can do:
var value = $("#element").val();
Where #element is the id of the element you wish to select.
You could try:
$('input.class').removeAttr('value');
$('#inputID').removeAttr('value');
A better way is:
$("#element").val(null);
Usual way to empty textbox using jquery is:
$('#txtInput').val('');
If above code is not working than please check that you are able to
get the input element.
console.log($('#txtInput')); // should return element in the console.
If still facing the same problem, please post your code.
Another way is:
$('#element').attr('value', '');
$('.reset').on('click',function(){
$('#upload input, #upload select').each(
function(index){
var input = $(this);
if(input.attr('type')=='text'){
document.getElementById(input.attr('id')).value = null;
}else if(input.attr('type')=='checkbox'){
document.getElementById(input.attr('id')).checked = false;
}else if(input.attr('type')=='radio'){
document.getElementById(input.attr('id')).checked = false;
}else{
document.getElementById(input.attr('id')).value = '';
//alert('Type: ' + input.attr('type') + ' -Name: ' + input.attr('name') + ' -Value: ' + input.val());
}
}
);
});
For me this was the best way to solve this:
$('yourElementName').val(null);

Categories