I have made an input box and i have cloned this input box to a div,let's name them ipbox1 and ipbox2, ipbox2 is the copy of ipbox1 now what i want to do is that when
i enter/change the value in either of them, the dom.value or $("#id").val() should return the updated the value. But now it's only functioning with the ipbox2.
What should i do?
fiddle
$("#ghj").click(function(){
$("#abc").val("Some text");
$("#abc").clone(true).appendTo("#pastehere");
})
$("#abc").on('change',function(){
alert();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type = "text" id = "abc">This is the first box
<div id = "pastehere">
</div>This is the cloned box
<br><button type = "button" id = "ghj">
Clone
</button>
I have update you fiddle: https://jsfiddle.net/gschambial/s6td1bof/7/
var initVal = $('#abc').val();
$("#ghj").click(function(){
$("#abc").val("Some text");
$("#abc").clone(true).appendTo("#pastehere");
})
$("#abc").on('change',function(){
alert();
initVal = $(this).val();
})
$("#get").click(function(){
alert(initVal);
})
You should not append a cloned element with an id as this creates invalid markup (two html elements with the same id).
If you want to be able to read the value of either of them independently, then check out this fiddle
If not, then I must be offtrack. Please add more details about what you need to achieve :)
HTML
<input type = "text" class = "abc">This is the first box
<div id = "pastehere">
</div>This is the cloned box
<br><button type = "button" id = "ghj">
Clone
</button>
JS
var initialInput = $(".abc");
$("#ghj").click(function(){
initialInput.val("Some text");
initialInput.clone(true).appendTo("#pastehere");
})
$(".abc").on('change',function(ev){
var targetInput = $(ev.target);
alert('myValueIs:' + targetInput.val())
});
Related
I would like to set the text of the label. Unfortunately the number 36 will change on each page refresh.
<label for="rn_TextInput_36_Incident.CustomFields.c.other_action_taken" id="rn_TextInput_36_Label" class="rn_Label">TEXT HERE</label>
<input type="text" id="rn_TextInput_36_Incident.CustomFields.c.other_action_taken" name="Incident.CustomFields.c.other_action_taken" class="rn_Text" maxlength="50" required="">
I can get the ID by using:
var id = document.getElementsByName('Incident.CustomFields.c.other_action_taken')[0].getAttribute('id');
How can I then use this to set the label text i.e. target the label by the value of the for attribute in JavaScript - not jQuery
So as mentioned, the number will change each time so I can't use the ID value of rn_TextInput_36_Label that the label currently has
Your element has the class rn_Label, so you can select by that.
var el = documment.querySelector(".rn_Label");
If you need to get more specific, you can include the tag name and part of the for attribute.
var el = documment.querySelector("label.rn_Label[for^=rn_TextInput_][for$=_Incident.CustomFields.c.other_action_taken]");
So this last selector selects the first element that:
has tag name label
has class name rn_Label
has a for attribute that starts with rn_TextInput_
has a for attribute that ends with _Incident.CustomFields.c.other_action_taken
And of course you can use querySelectorAll to select all elements on the page that meet that criteria.
you can work same as this code:
var input = document.getElementsByName('Incident.CustomFields.c.other_action_taken')[0];
if(input.labels.length > 0) {
var labelID = input.labels[0].id;
document.getElementById(labelID ).innerHTML = 'New Text for this lable';
}
else {
alert('there is no label for this input');
}
https://jsfiddle.net/SETha/75/
var id = document.getElementsByName('Incident.CustomFields.c.other_action_taken')[0].getAttribute('id');
document.querySelector("label[for='"+id+"']").innerText = 'new text';
It gets the ID and then uses querySelector to get the related label and sets the innertext
I have a drag and drop thing which uses clone. I am having a problem with the date clone though because of datepicker. Therefore, I need to make sure each cloned datepicker has a unique id. A cloned element looks like the following
<div data-type="date" class="form-group">
<label class="control-label col-sm-5" for="dateInput">Date Input:</label>
<div class="col-sm-3">
<input type="text" name="dateInput[]" class="form-control date_picker" id="dateInput">
</div>
</div>
So if I clone two date inputs, I will have two of the above. Now on submit, I clean all of the cloned html, doing things like removing the data-type. At this stage, if there is a cloned date input, I need to give it a unique id. At the moment I am doing this
$("#content").find(".form-group").each(function() {
var html = $(this).attr('class', 'form-group')[0].outerHTML.replace(/ data-(.+)="(.+)"/g, "");
var input = $(this).find('input');
var i = 0;
if(input.attr('id') == 'dateInput') {
alert("TEST");
input.attr("id",'dateInput' + i).datepicker();
i++;
}
console.log(html);
dataArray.push(html);
});
The TEST alert fires twice as it should do if I clone 2 date inputs. However, the id attributes do not seem to change when I output the html to the console. I have set up the following Fiddle to demonstrate that the id of the element is not changing.
Any advice on getting this to change appreciated.
Thanks
Try defining dataArray, i outside out submit event, .each() , using .map() , .get() , .attr(function() {index, attr}) , .outerHTML
$(function() {
// define `i` , `dataArray`
var i = 0, dataArray = [];
$('#content').submit(function(event) {
event.preventDefault();
$("#content").find(".form-group").each(function() {
var html = $(this).attr('class', '.form-group')[0]
.outerHTML.replace(/ data-(.+)="(.+)"/g, "");
dataArray.push($(html).map(function(_, el) {
// adjust `input` `id` here , return `input` as string
return $(el).find("input").attr("id", function(_, id) {
return id + (++i)
})[0].outerHTML
}).get()[0])
});
$("#output")[0].textContent = dataArray.join(" ");
console.log(dataArray)
});
});
jsfiddle https://jsfiddle.net/mLgrfzaL/2/
Javascript:
function submitComment(e){
e.preventDefault();
var comment = $('#????').val(); // how do I get the ID?
// ajax
}
Comment form:
<form id="comment-form[id]" onsubmit="submitComment(event)">
<input id="comment-input[id]" type="text" placeholder="Comment...">
</form>
[id] is the variable ID of the specific form. The reason it has an ID is because I have a for loop that displays a whole list of posts, and each post has its own comment form (think Facebook).
What I want to know is how I can get the value (text) of the comment input box when they submit it based on the ID of the form that was submitted.
You can use event.target.
var comment = $('input[id^="comment-input"]',e.target).val()
This will give you input value.
e.target will give you the current form.
Then you can use [^=""] - attribute starts with selector to find the input element.
how I can get the value (text) of the comment input box based on the ID of the form that was submitted
var formID = e.target.id; //get form ID
var comment = $('#'+formID+' input[id^="comment-input"]').val()
//use $('#parent child') selector.
With your setup(HTML/javascript) you can do this with pure javascript like
function submitComment(e) {
var id = e.target.id;
id = id.match(/\[(.*?)\]/)[1];
console.log(id);
var comment = document.getElementById('comment-input['+id+']').value;
console.log(comment);
}
function submitComment(e){
var id = e.target.id;
id = id.match(/\[(.*?)\]/)[1];
console.log(id);
var comment = document.getElementById('comment-input['+id+']').value;
console.log(comment);
}
<form id="comment-form[0]" onsubmit="submitComment(event)">
<input id="comment-input[0]" type="text" placeholder="Comment...">
<input type="submit" placeholder="submit">
</form>
function submitComment(e){
e.preventDefault();
var comment = $('input[id^="comment-input"]').val();
// ajax
}
Use of jquery start-with selector can be helpful.
function submitComment(e){
e.preventDefault();
// e.currentTarget gives you the form element and then you can extract its id
var formElementId = $(e.currentTarget).attr("id");
// Then replace the form text with input which will be your comment input id
var commentElementId = formElementId.replace("form", "input");
var comment = $(commentElementId).val(); // how do I get the ID?
// ajax
}
I've read many blogs and posts on dynamically adding fieldsets, but they all give a very complicated answer. What I require is not that complicated.
My HTML Code:
<input type="text" name="member" value="">Number of members: (max. 10)<br />
Fill Details
So, a user will enter an integer value (I'm checking the validation using javascript) in the input field. And on clicking the Fill Details link, corresponding number of input fields will appear for him to enter. I want to achieve this using javascript.
I'm not a pro in javascript. I was thinking how can I retrieve the integer filled in by the user in input field through the link and displaying corresponding number of input fields.
You could use an onclick event handler in order to get the input value for the text field. Make sure you give the field an unique id attribute so you can refer to it safely through document.getElementById():
If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">. Create new elements by means of document.createElement(), and use appendChild() to append each of them to the container. You might be interested in outputting a meaningful name attribute (e.g. name="member"+i for each of the dynamically generated <input>s if they are to be submitted in a form.
Notice you could also create <br/> elements with document.createElement('br'). If you want to just output some text, you can use document.createTextNode() instead.
Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes() and removeChild() together.
<html>
<head>
<script type='text/javascript'>
function addFields(){
// Generate a dynamic number of inputs
var number = document.getElementById("member").value;
// Get the element where the inputs will be added to
var container = document.getElementById("container");
// Remove every children it had before
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
// Append a node with a random text
container.appendChild(document.createTextNode("Member " + (i+1)));
// Create an <input> element, set its type and name attributes
var input = document.createElement("input");
input.type = "text";
input.name = "member" + i;
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement("br"));
}
}
</script>
</head>
<body>
<input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
Fill Details
<div id="container"/>
</body>
</html>
See a working sample in this JSFiddle.
Try this JQuery code to dynamically include form, field, and delete/remove behavior:
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e) {
e.preventDefault();
if (x < max_fields) {
x++;
$(wrapper).append('<div><input type="text" name="mytext[]"/>Delete</div>'); //add input box
} else {
alert('You Reached the limits')
}
});
$(wrapper).on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container1">
<button class="add_form_field">Add New Field
<span style="font-size:16px; font-weight:bold;">+ </span>
</button>
<div><input type="text" name="mytext[]"></div>
</div>
I have two input type = text. The text of the textbox is populated from a custom date picker module. I want to change the content of second text box when the text of first text box is changed.
<input type = "text" id = "one">
<br>
<input type = "text" id = "two">
<br>
<button onclick="myFunction()">Click me</button>
Javascript
function myFunction()
{
document.getElementById('two').value = 'hello';
}
Here I have just simulated the change of textbox 'two' on button click but actually it is changed by some other methods.
I want to change the text of textbox 'one' when value of textbox 'two' is changed.
Events like onchange and keyup wont work as the text is explicitly changed.
Checking the value of both text boxes for equality at interval of 1 sec is also not an option for me.
Plain Javascript or jQuery is fine.
Here is an example using jQuery:
Live view:
http://jsbin.com/aqiyaz/1/
Code:
http://jsbin.com/aqiyaz/1/edit
My solution is built on two javascript functions as follows:
function myFunction()
{
ob = document.getElementById('two')
ob.value = 'hello';
ob.focus();
ob.blur();
}
function sync(){
document.getElementById('one').value = document.getElementById('two').value
}
here is the HTML:
<input type = "text" id = "one">
<br>
<input type = "text" id = "two" onblur="sync()">
<br>
<button onclick="myFunction()">Click me</button>
The following is a demo: http://jsfiddle.net/saidbakr/hD6Sx/