I have div with generated input fields. After button click I want to refresh div and then set values.
<div>
<input id="1" name="1" type="text" />
<input id="2" name="2" type="text" />
</div>
<button type="button" onClick="change();">Change</button>
Javascript function:
function change(){
$('div').load(' div');
$("input[type='text']").val("some text");
}
Why after load I can't set values for input? How can I solve it? Thanks
.load() is asynchronous. So when you do this:
$('div').load(' div');
$("input[type='text']").val("some text");
That second line executes before the content has been loaded. In order to respond to the completion of the content being loaded, you need to use the callback function:
$('div').load(' div', function () {
$("input[type='text']").val("some text");
});
Related
I have four image buttons with onclick events attached to them two pairs of two. I'm trying to replace those image buttons with text buttons and reattach the onclick function to the next text buttons. These buttons are not always on the page and I'm confined to using jQuery 1.4 otherwise .prop would make this a lot easier.
Consider this HTML:
<input type="image" src="path/to/image.gif" class="one" onclick="function()" />
<input type="image" src="path/to/image.gif" class="one" onclick="function()" />
<input type="image" src="path/to/image2.gif" class="two" onclick="function()" />
<input type="image" src="path/to/image2.gif" class="two" onclick="function()" />
I wrote the following jQuery code to get the onclick function, the inputs and rebind the onclick function.
$('input.one').each(function(){
var oneOnClick = $(this).attr('onclick');
$(this).replaceWith('<input type="button" value="one" class="one" onclick="'+oneOnClick+'" />');
)};
And the same for .two. I found out that the way the value of the onclick attribute is returned in jQuery means this cannot be done.
Using some resources online I updated my code to look like this:
var oneOnClick = $('input.one').first().attr('onclick');
var twoOnClick = $('input.two').first().attr('onclick');
$('input.one').each(function(){
$(this).replaceWith('<input type="button" class="one" value="one"/>');
});
$('input.two').each(function(){
$(this).replaceWith('<input type="button" class="two" value="two"/>');
});
$('input.one').live("click", oneOnClick);
$('input.two').live("click", twoOnClick);
But I'm getting an error
TypeError: undefined is not an object (evaluating 'b.split')
when input.one doesn't exist.
How can I make this work?
Please try the following code to bind onClick event
$(document).ready(function(){
$('input.one').each(function(){
$(this).attr('type',"button");
});
});
Well I suggest you to go with your first opted method:
Check this DEMO
function clickOne()
{
alert('hi');
}
function clickTwo()
{
alert('helleo');
}
$(document).ready(function(){
var oneOnClick = $('input.one').first().get(0).attributes.onclick.nodeValue;
var twoOnClick = $('input.two').first().get(0).attributes.onclick.nodeValue;
$('input.one').each(function(){
$(this).replaceWith('<input type="button" value="one" class="one" onclick="'+oneOnClick+'" />');
});
$('input.two').each(function(){
$(this).replaceWith('<input type="button" value="two" class="two" onclick="'+twoOnClick+'" />');
});
$('input.one').live("click", oneOnClick);
$('input.two').live("click", twoOnClick);
});
POINT TO NOTE:
$('input.one').attr('onclick') or $('input.two').attr('onclick') holds the value of the onclick attribute (which is a string). However, because the browsers treat the event attributes in a different way, they are
returned with function onclick() { clickOne() } and you know
about this. Thus, if you want to directly call the function, you'll
have to either strip the
function() {} or call it immediately or get it using
get(0).attributes.onclick.nodeValue
wrap clickOne and clickTwo in head and remaining things on document.ready
Say I have this text box:
<input type="text" id="myText" placeholder="Enter Name Here">
Upon pressing a button, I would like to send the value entered into this div:
<div id="text2"></div>
I'm not entirely sure how to do this. Do I create a function and call it to the div? How would I do that?
Could someone clear this up for me? Thanks.
Add an onclick to your button:
<input type="button" id="somebutton" onclick="addText()">
Then write the javascript:
function addText()
{
document.getElementById('text2').innerHTML = document.getElementById('myText').value;
}
Solution using onclick event:
<input type="text" id="myText" placeholder="Enter Name Here">
<div id="text2"></div>
<button id="copyName" onclick="document.querySelector('#text2').innerHTML = document.querySelector('#myText').value" value="Copy Name"></button>
JSFiddle: http://jsfiddle.net/3kjqfh6x/1/
You can manipulate the content inside the div from javascript code. Your button should trigger a function (using the onclick event), which would access the specific div within the DOM (using the getElementById function) and change its contents.
Basically, you'd want to do the following:
<!DOCTYPE html>
<html>
<script>
function changeContent() {
document.getElementById("myDiv").innerHTML = "Hi there!";
}
</script>
<body>
<div id="myDiv"></div>
<button type="button" onclick="changeContent()">click me</button>
</body>
</html>
Mark D,
You need to include javascript to handle the button click, and in the function that the button calls, you should send the value into the div. You can call $("#myText").val() to get the text of the text box, and $("#txtDiv").text(txtToAppend) to append it to the div. Please look at the following code snippet for an example.
function submitTxt() {
$("#txtDiv").text($("#myText").val())
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="myText" placeholder="Enter Name Here">
<button onclick = "submitTxt()"> Submit </button>
<div id="txtDiv"> </div>
HTML could be:
<input type='text' id='myText' placeholder='Enter Name Here' />
<input type='button' id='btn' value='click here' />
<div id='text2'></div>
JavaScript should be external:
//<![CDATA[
var pre = onload; // previous onload? - window can only have one onload property using this style of Event delegation
onload = function(){
if(pre)pre();
var doc = document, bod = doc.body;
function E(e){
return doc.getElementById(e);
}
var text2 = E('text2'); // example of Element stored in variable
E('btn').onclick = function(){
text2.innerHTML = E('myText').value;
}
}
//]]>
I would recommend using a library like jQuery to do this. It would simplify the event handling and dom manipulation. None the less, I will include vanilla JS and jQuery examples.
Assuming the HTML in the body looks like this:
<form>
<input id="myText" type="text" placeholder="Enter Name Here">
<br>
<input type="submit" id="myButton">
</form>
<div id="text2"></div>
The Vanilla JS example:
//Get reference to button
var myButton = document.getElementById('myButton');
//listen for click event and handle click with callback
myButton.addEventListener('click', function(e){
e.preventDefault(); //stop page request
//grab div and input reference
var myText = document.getElementById("myText");
var myDiv = document.getElementById("text2");
//set div with input text
myDiv.innerHTML = myText.value;
});
When possible avoid using inline onclick property, this can make your code more manageable in the long run.
This is the jQuery Version:
//Handles button click
$('#myButton').click(function(e){
e.preventDefault(); //stop page request
var myText = $('#myText').val(); //gets input value
$('#text2').html(myText); //sets div to input value
});
The jQuery example assumes that you have/are adding the library in a script tag.
This is my code:
Javascript:
$(".test").on("focusout", function (e) {
$("#output").append("Lost focus<br>");
});
HTML:
Inputs inside div:
<div class="test">
<input type="text" />
<input type="text" />
</div><br>
Inputs outside div:<br>
<input type="text" />
<div id="output">
</div>
I want to detect if user leaves "div.test". Unfortunately, "focusout" works also when I move focus to other object inside this div.
Look at this fiddle: http://jsfiddle.net/Piotrek1/wfukje3g/6/
Click on first input and use Tab to switch through textboxes. "
Lost focus" should appear only if user move out from the div, but it happens always. Why is that and how to change it?
The $ operator returns a collection. You have two inputs inside the <div class="test">. So it matches all elements and children with the .test class.
I think what you want two divs with separate input elements and two different classes OR, use an ID on the actual input element so the $ operator only matches the input id you want this event to fire on. http://jsfiddle.net/wfukje3g/7/
$("#test").on("focusout", function (e) {
$("#output").append("Lost focus<br>");
});
<div class="sometest">
<input id="test" type="text" />
<input type="text" />
</div><br>
Inputs outside div:<br>
<input type="text" />
<div id="output">
</div>
I have implemented piece of code to handle div focus out
$(document).ready(function () {
var count = 1;
$("#name").focusout(function (e) {
if($(this).has(e.relatedTarget).length === 0) {
$("#output").append("<label style='width:100%;'>"+ count++ +" Name div focus out </label>");
}
});
});
Inputs inside div:
<div id="name" class="test">
<input type="text" id="firstname"/>
<input type="text" id="lastname"/>
</div>
Inputs outside div:<br>
<input type="text" id="dob"/>
<div id="output" style="width:100%"></div>
In this piece of code I have used relatedTarget.
relatedTarget will provide the next focused element If next element is not the child of this div then it is div focus out.
Try this in your code.
I hope this will be helpful.
Thanks
JSFIDDLE LINK - Sample code
I have a form tag with a progress tag and three submit as following:
<form>
<progress min="0" max="100" value="0"></progress>
<input type="submit" value="submit1">
<input type="submit" value="submit2">
<input type="submit" value="submit3">
</form>
I have a little js code which listens click event and changes the value of progress bar.
;(function(){
document.body.addEventListener('click', function(){
var p = document.querySelector('progress');
var s = document.querySelector('input');
var val;
if(s.value=="submit1"){
val=33;
}
if(s.value=="submit2"){
val=66;
}
if(s.value=="submit3"){
val=100;
}
p.value=val;
}, false);
}());
But the progress bar is not working as expected.
Any point where I can solve this?
About document.querySelector:
Returns the first element within the document (using depth-first pre-order traversal of the document's nodes) that matches the specified group of selectors.
So, the code always will return "submit1", because it is the first element in the document.
Also form's submit make callback to the page, and you can't see the changes, because the code will return to initial stage.
If you doesn't want to do the callback, just change inputs types to "button".
Also, I offer you to attach onclick event to each button and call functionality that you want.
EDIT: The worked code bellow.
<form>
<progress min="0" max="100" value="0" id="progressBar1"></progress>
<input type="button" value="submit1" onclick="SubmitProgress(33);" />
<input type="button" value="submit2" onclick="SubmitProgress(66);" />
<input type="button" value="submit3" onclick="SubmitProgress(100);" />
</form>
<script type='text/javascript'>
function SubmitProgress(valueToSet) {
document.getElementById("progressBar1").value = valueToSet;
}
</script>
In your javascript - a typo might is what killed the script. Instead of using
;(function(){
Use this:
$(function(){
My JS is as follows:
$(document).ready(function(){
$('#data1').change(function(){
title = $('#title1').val();
url = $('#url1').val();
$.post('library/edit.php',{title:title, url:url},function(res){
alert ("updated !");
});
});
});
and my HMTL-markup:
<div id="data1">
<input name="title1" type="text" id="title1" />
<input name="url1" type="text" id="url1" />
</div>
I wrote that code to call to a PHP file on change of textbox.
that code works as expected.
But now I've added more textboxes as follows:
<div id="div1"><input name="title1" type="text" id="title1" />
<input name="url1" type="text" id="url1" /></div>
<div id="div2"><input name="title2" type="text" id="title2" />
<input name="url2" type="text" id="url2" /></div>
<div id="div3"><input name="title3" type="text" id="title3" />
<input name="url3" type="text" id="url3" /></div>
Now I want the same functionality so that any of these textboxes works like title1 in my earlier code. So if input#title-3 is changed I want the change to be uploaded via POST to my PHP-script.
Important: The number of boxes are dynamic.
$(document).ready(function(){
$('#data1').on('change','[id^=title],[id^=url]',function(){
var index = $(this).attr('id').replace('title',"").replace('url',"");
var title = $("#title" + index).val();
var url = $("#url" + index).val();
var hid = $("#hid" + index).val();
// you can put in here in sequence all the fields you have
$.post('library/edit.php',{title:title, url:url, hid : hid},function(res){
alert ("updated !");
});
});
});
so by this answer if any text box whoes id starts with title changes.
the function passed in will be invoked.
indezx variable will store the index of the group of the elements that are changing. and then is being callculated by removing title from title1 or title2
I think the answer you have it right here:
I wrote that code to call to php file on change of textbox.
That script (jQuery I guess) it must be associatte with the $('#xxx1').onchange() right? (or similar)
If you modify the function, add a class to the input field (also in the php) and each time you call the function, start listening again.. I think you can call any function you may want.
Example (guessing your code)
HTML
<div id="data1" class="dynamicDiv">
<input name="title1" type="text" id="title1" />
<input name="url1" type="text" id="url1" />
</div>
jQuery
// enable the function on document ready
$(document).ready(function(){
startListening('.dynamicDiv');
});
// each time an ajax call is completed,
// run the function again to map new objects
$(document).ajaxComplete(function(){
startListening('.dynamicDiv');
});
// and finally the function
function startListening(obj){
$(obj).onchange(function(){
// ajax call
// function call
// or whatever...
});
}
PHP
// some code....
// some code....
// remember here to add "dynamicDiv" as a class in the object
return object;
Since your elements are dynamically generated you need to use event delegation, then you can use [id^="value"] to select the appropriate elements based on the first part of their id attribute
$(document).ready(function(){
$(document).on('change','[id^="data"]',function(){
var title = $(this).find('[id^="title"]').val();
var url = $(this).find('[id^="url"]').val();
var hidden = $(this).find('[id^="hid"]').val();
$.post('library/edit.php',{title:title, url:url, hid:hidden},function(res){
alert ("updated !");
});
});
});
Note: I suggest you bind to the closest parent of your data divs that is present at page load instead of binding to the document