$('<p><input type="text" class = "class-'+ (++i) +'" onclick="'(+ this.value = ''; +)'" value="Enter Choice #' + i + '"/></p>')
I'm not sure if this is the correct syntax or not, but whatever I am using is not working. ANy help? Thanks
HTML:
<input type="text" class="class-1" value="Enter Choice #1">
<input type="text" class="class-2" value="Enter Choice #2">
JQUERY:
$(document).ready(function() {
$('input[class^="class-"]').focus(function() {
var $input = $(this);
if($input.val() == $input.data('default_val') || !$input.data('default_val')) {
$input.data('default_val', $input.val());
$input.val('');
}
});
$('input[class^="class-"]').blur(function() {
var $input = $(this);
if ($input.val() == '') $input.val($input.data('default_val'));
});
});
Above code clear the value when the textfields gets focus and adds the default value when textfield is empty on lost focus (blur).
Updated fiddle: http://jsfiddle.net/K3Sx7/4/
EDIT: updated code to conform question.
Add an id to your input field:
<input id="myinput"...
Then add this code in your $(document).ready(... call:
$('#myinput') // get element whose id is 'myinput'
.click(function() { // bind a click handler
$(this).val('') // clear field
.unbind('click'); // unbind click handler to avoid field being cleared again
})
I think you can do it without jQuery
try this
<p><input type="text" class = "class-1" onclick="this.value='';" value="Enter Choice # 1"/></p>
To do it inline like that, you need to keep the this.value='' as part of the string:
$('<p><input type="text" class = "class-'+ (++i) +'" onclick="this.value=\'\'" value="Enter Choice #' + i + '"/></p>');
Notice the " onclick="this.value=\'\'", where the single quotes are escaped to keep the main string from being terminated.
Here's a working example for you.
var i = 0;
$('<input type="text" class="class-'+ ++i +'" value="Enter Choice #' + i + '"/>')
.click(function(){
this.value = '';
})
.wrap('<p />')
.parent()
.appendTo('#container');
http://jsfiddle.net/jruddell/FVqjQ/
Related
Hi I want to create a stamp script and I want the user to enter his name and address in three fields,
then he should see the fields later in the stamp edition?
I have 3 input fields where the user can give in his data,
now i will give this data in a new class. This is what i have:
window.onload = function() {
$( "#Text1" )
.keyup(function() {
var value = $( this ).val();
$( ".ausgabe" ).text( value );
})
.keyup();
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="Text1">
<input type="text" id="Text2">
<input type="text" id="Text3">
<div class="ausgabe"></div>
It looks like you want to mimic what the user is typing in the text inputs and show it in ausgabe. If that's what you want, then you can tie the keyUp event to each of the inputs.
$(input [type='text']).keyUp(function() {
var value = $(this).val();
$('.ausgabe').text(value);
}
But this will overwrite .ausgabe every time text is entered into a different input.
You could get the value of .ausgabe every time keyUp fires and pre-pend that value:
So you may want to have a button that renders each input's value into .ausgabe:
<button>.click(function() {
$(input[type="text"]).each(function() {
var boxText = $(this).val(); //text box value
var aus = $('.ausgabe').text(); //ausgabe value
$('.ausgabe').text(boxText + ' ' + aus); //combine the current text box value with ausgabe
})
})
As you have not made it very clear what you are trying to accomplish, I am providing a simple example that might send you down the right path.
$(function() {
function updateDiv(source, target) {
var newVal = "";
source.each(function() {
newVal += "<span class='text " + $(this).attr('id').replace("Text", "item-") + "'>" + $(this).val() + "</span> ";
});
target.html(newVal);
}
$("[id^='Text']").keyup(function(e) {
updateDiv($("input[id^='Text']"), $(".ausgabe"));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="Text1">
<input type="text" id="Text2">
<input type="text" id="Text3">
<div class="ausgabe"></div>
Since you already seem to understand .html() and .text(), we can look at the Selector. The one used will select all elements with an ID Attribute of Text in the beginning of the string. See More: https://api.jquery.com/category/selectors/attribute-selectors/
I am running a loop which is appending input fields. Now, as I am using a loop, all the attributes are similars. So, when I need to grab any one of the then I am grabbing more than one field.
How do I dynamically change the attributes according to the index, so that I can grab the correct input field ?
ebs_no = data.number_ebs;
for(i=0;i<ebs_no;i++){
$('form.ebs').append("<br>EBS"+(i+1)+"</br>");
$('form.ebs').append('<br> SNAPSHOTNO <input type="text" name="'+i+'"></br>');
$('form.ebs').append('<input type="submit" name="submit">');
$('[name='+i+']').on('submit',function(){
alert($('[name='+i+']').val());
});
}
Replace this:
alert($('[name='+i+']').val());
by this:
alert($(this).val());
The code $(this) refers to the element being treated
Your are looking for event delegation.It is used for created Dynamically DOM elements and use class instead of iterare i in the loop
ebs_no = data.number_ebs;
for (i = 0; i < ebs_no; i++) {
$('form.ebs').append("<br>EBS" + (i + 1) + "</br>");
$('form.ebs').append('<br> SNAPSHOTNO <input type="text" class="someClass" name="' + i + '"></br>');
$('form.ebs').append('<input type="submit" name="submit">');
$('[name=' + i + ']').on('submit', function () {
alert($('[name=' + i + ']').val());
});
}
$(document).on('submit', '.someClass', function () {
alert($(this).val());
});
I have a form containing some dynamically added date fields using jQuery, In order to handle their params submitted I need to count the number of those fields, then inside the controller I can make a loop based on that number:
application.js
$(function() {
var scntDiv = $('#foo');
var i = $('#foo div.bar').size();
$(document).on('click', '#addField', function() {
$('<div class="bar"><input type="text" id="start" name="start_'+ i +'"><input type="text" id="end" name="end_'+ i +'"></div>').appendTo(scntDiv);
i++;
return false;
});
Saying I added n input, then the html output will be:
<input type="text" id="start" name="start_1">
<input type="text" id="end" name="end_1">
.
.
.
<input type="text" id="start" name="start_n">
<input type="text" id="end" name="end_n">
My question is, how to access that "n" inside my controller?
I have to store all the dates range in one array then create multiple records based on each date.
Another option, close to how nested_attributes are implemented (not the most beautiful javascript you'll see out there, but you get the spirit) :
$(function() {
var $scntDiv = $('#foo');
$('#addField').click( function(){
var index = $scntDiv.find( '.bar' ).size();
$(
'<div class="bar">' +
'<input type="text" class="start" name="ranges[' + index + '][start]">' +
'<input type="text" class="end" name="ranges[' + index + '][end]">' +
'</div>'
).appendTo( $scntDiv );
return false;
});
});
This will build a hash like this :
>> params[:ranges]
=> {"0" => {"start" => "a_date_string", "end" => "another_date_string"},
"1" => {"start" => "a_date_string", "end" => "another_date_string"} }
it's then easy to process this hash, even using mass assignment :
class MyClass
def ranges= ranges
ranges.each do |*,attributes|
# whatever logic pleases you, self.ranges.build( attributes ) for instance
end
end
end
however, if you go this way, you better use directly nested_attributes, except if you have a very convoluted logic to perform. Nested attributes come with a lot of goodies like auto instantiation of child records, record deletion management, auto-rejection of some attributes if needed, they work well with the fields_for form helper, etc. It's native to rails, so why bother and reinvent the wheel ?
This will help.
$(function() {
var scntDiv = $('#foo');
$('#addField').click(function(){
$('<div class="bar"><input type="text" id="start" name="start[]"><input type="text" id="end" name="end[]"></div>').appendTo(scntDiv);
return false;
});
});
This will send the params like below. for example
"start"=>["1", "2", "3"], "end"=>["11", "22", "33"]
I want to get the value of another textbox and input it in realtime into the other textbox.
HOW CAN I DETECT IF TEXT_3 WAS CHANGED? IF TEXT_3 VALUE CHANGED, IT MUST BE INPUTTED TO TEXT_4
For your convenience, here is the code and the demo:
**HTML**
<label>TEXT 1: </label><input type="text" id="text_1" value=""/>
<label>TEXT 2: </label><input type="text" id="text_2" value=""/>
<label>TEXT 3: </label><input type="text" id="text_3" value=""/>
<label>TEXT 4: </label><input type="text" id="text_4" value=""/>
**JAVASCRIPT**
/* INPUT TEXT_1 AND TEXT_2 VALUE TO TEXT_3 ON TEXT_1 KEYUP*/
$("#text_1").keyup(function() {
$("#text_3").val($("#text_1").val() + " " + $("#text_2").val());
})
/* INPUT TEXT_1 AND TEXT_2 VALUE TO TEXT_3 ON TEXT_1 AND TEXT_2 KEYUP*/
$("#text_2").keyup(function(){
$("#text_3").val($("#text_1").val() + " " + $("#text_2").val());
})
/* HOW CAN I DETECT IF TEXT_3 WAS CHANGED? IF TEXT_3 VALUE CHANGED, IT MUST BE INPUTTED TO TEXT_4*/
/* not working solution */
$("#text_3").change(function(){
$("#text_4").val($("#text_3").val());
})
DEMO: http://jsfiddle.net/8eXRx/7/
Thanks for responses!
Add change() after your textbox3.val(),
like below:
$("#text_1").keyup(function() {
$("#text_3").val($("#text_1").val() + " " + $("#text_2").val()).change();
})
/* INPUT TEXT_1 AND TEXT_2 VALUE TO TEXT_3 ON TEXT_1 AND TEXT_2 KEYUP*/
$("#text_2").keyup(function(){
$("#text_3").val($("#text_1").val() + " " + $("#text_2").val()).change();
})
http://jsfiddle.net/8eXRx/12/
The problem is that you can't bind special event to check that the textbox value was changed using JavaScript and not manually. To solve the task, one option is to use the same keyup event for both text_1 and text_2. JQuery will add the new handler to the existing handlers:
$("#text_1, #text_2").keyup(function(){
$("#text_4").val($("#text_3").val());
})
DEMO: http://jsfiddle.net/8eXRx/11/
the change event fires after the input field has lost it's focus. If you want to update it in realtime you also need the keyup event, so something like this:
$("#text_3").keyup(function(){
$("#text_4").val($("#text_3").val());
})
Try:
$("#text_3").keyup(function(){
cur_val = $(this).val(); //grab #text_3's current value
$(this).val(cur_val); // this is optional, but keep for sake
$("#text_4").val(cur_val); //set #text_4's value as what #text_3 is having
});
Try this.. n1 and n2 are ids of textbox
$(document).ready(function(){
$(':input').keyup(function(){
$("#n2").val($("#n1").val()).change();
});
});
I'm pretty new to JQuery, as you can tell by my question...
The user can append many new input fields to the form. This works great, but how can they delete a specific field? If they append 5 input fields, how do they delete lets say the third field?
Below is my following code. What is currently does is always delete the first item when clicked.
$("#addNewItem").click(function(){
$("#invoice_items").append('<input type="text" name="name[]" value="name" id="item_name" class="item_name" /><img src="images/delete.png" />');
});
$("#delete_input").live("click", function(){
$("#item_name").remove();
$(this).remove();
});
How about using additional container for inputs?
http://jsfiddle.net/dFpMV/
$("#addNewItem").click(function(){
$("#invoice_items").append('<div class="input-container"><input type="text" name="name[]" value="name" id="item_name" class="item_name" />X<img src="images/delete.png" /></div>');
});
$("#delete_input").live("click", function(){
$(this).parent().remove();
});
First, count the number of inputs you've added and store it in a variable.
Then, when you add the element, make a unique identifier based on that number.
$("#invoice_items").append('<input type="text" name="name[]" value="name" id="item'+count'" class="item_name" /><img src="images/delete.png" />');
I would avoid using the specific item name as the id in this case, use something generic like item0, item1 etc.
Then, to remove
$("#item" + desiredNumber).remove();
$(this).remove();
all links need to have unique id. Allowing to append element with specified id twice is an error. What you could do is to add an artificial number at the end of id to make them unique. I would wrap both input and link into a div, i would assign an unique id to it, assign a class to delete link instead of id and remove div like ($this).parent().remove()
If you are using jQuery 1.7+: Also note that .live() is deprecated and you should use .on() instead (note that syntax is however a little bit different).
I made 2 examples for you and adding a dummy variable so you can see whats happend:
1 If you know how to DOM will look like and the relationship between the delete link and the input you can simply traversing to the previous item.
$("#delete_input").live("click", function(){
$(this).prev().remove();
$(this).remove();
});
http://jsfiddle.net/JgKRw/ Example nr 1 in action
2 You give each item a unique number when you add them to the DOM.
var dummyId = 0;
$("#addNewItem").click(function(){
dummyId++;
$("#invoice_items").append('<input type="text" name="name[]" value="name ' + dummyId + '" id="item_name" class="item_name" data-id="' + dummyId + '" /><a data-id="' + dummyId + '" href="#" id="delete_input">' + dummyId + '<img src="images/delete.png" /></a>');
});
$("#delete_input").live("click", function(){
var deletedId = $(this).data("id"); // Get the ID of the clicked link
$("input[data-id='" + deletedId + "']").remove(); // Seach for an input which has the ID
$(this).remove();
});
http://jsfiddle.net/JgKRw/1/ Example nr 2 in Action
I would implemented number 2, couse else you have to take care of the script if you want to change the UI.
Btw you should only have one element assigned to an ID, so change your ID and use classes insteed.
http://api.jquery.com/class-selector/
Given the markup you appending it should be simply $(this).prev().remove(); and ignore the IDs.
Here's my fiddle:
http://jsfiddle.net/JfUAa/
(function () {
var count = 0,
items = document.getElementById("input_items"),
$items = $(items),
tpl = '<div><input type="text" id="{{id}}" />delete</div>';
function addItem(){
$items.append(tpl.replace("{{id}}", count++));
}
function remove(){
items.removeChild(this.parentNode);
}
$("#addNewItem").click(addItem);
$items.on("click", "a", remove);
}());