I have a pretty simple query here. I have a view page with an div and a form element. This is how they look.
<div id="candy" value="valueOfCandy" ></div>
<input type="text" value="javascript:document.getElementById('candy').getAttribute('value')"/>
I need to access the value of candy inside input's attribute (it can be any attribute).
I tried the code as I have shown above but that didnt work. I researched on StackOverflow too but couldnt find anything satisfactory. Please help out.
Edit: Thank you everyone. I found the answer to that, which I am gonna mark. Also, deleting this question so that it doesnt confuse someone else.
If I assume you want to do this at page load, do it like this
Note 1, custom attributes should have a data- prefix and use .dataset to access its value.
Note 2, for older browsers like IE10 and below, you need getAttribute (as in 2nd sample below).
Stack snippet 1
<div id="candy" data-value="valueOfCandy"></div>
<input id="candy2" type="text" value="" />
<script>
document.getElementById('candy2').value =
document.getElementById('candy').dataset.value
</script>
Stack snippet 2
<div id="candy" data-value="valueOfCandy"></div>
<input id="candy2" type="text" value="" />
<script>
document.getElementById('candy2').value =
document.getElementById('candy').getAttribute('data-value')
</script>
Do it in JavaScript outside of code but after the objects exist.
Here's an example of how to achieve this:
var candy = document.getElementById('candy').getAttribute('data-value');
document.getElementById('input').value = candy;
<div id="candy" data-value="valueOfCandy" ></div>
<input id="input" type="text"/>
As mentioned in the comments, please make sure your JavaScript code is loaded after your markup. There are various ways to do this, including waiting for the dom to load.
See $(document).ready equivalent without jQuery and How does the location of a script tag in a page affect a JavaScript function that is defined in it? for more information.
Try this
document.getElementById('input').value = document.getElementById('candy').dataset.value
<div id="candy" data-value="valueOfCandy" ></div>
<input id="input" type="text" value=""/>
This is not how you should be doing this.
JavaScript should be separated out of the HTML completely to avoid a whole host of issues. Including JavaScript in the HTML as you are attempting is a 20+ year old technique that was used before we had standards.
Next, a div element can't have a value attribute. value is only for form fields. But, you can create a data-* attribute, which allows for you to create custom attributes. You can then extract that value using the .dataset property.
See below:
// This code would be placed inside of <script> and </script> tags and the whole
// thing would be placed just before the closing body tag (</body>).
document.getElementById("result").value = document.getElementById('candy').dataset.value;
<div id="candy" data-value="valueOfCandy"></div>
<input type="text" id="result">
Put that code either within a script tag or in a separated js file.
Further, always bind the event DOMContentLoaded when you need to manipulate DOM elements.
DOMContentLoaded
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A very different event load should be used only to detect a fully-loaded page. It is an incredibly popular mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.
This way, your logic is totally consistent.
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
document.getElementById('candy2').value =
document.getElementById('candy').getAttribute('value')
});
<div id="candy" value="valueOfCandy"></div>
<input id="candy2" type="text" value="" />
A recommendation is to use data-attributes because the value attribute is related to form fields:
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
document.getElementById('candy2').value =
document.getElementById('candy').dataset.value;
});
<div id="candy" data-value="valueOfCandy"></div>
<input id="candy2" type="text" value="" />
Related
I've created a simple js function called from a button-onclick to do something straight forward, submit the data 'selected' and open a new tab. This was a single use case, worked fine for this one case. But NOW, as I'm scripting out more and more widgets within my feature, (tabs presenting different tools, within the same DOM). I'm finding way harder to keep the DRY.
I want to set up the forms to have same general inputs, get which form it is by the form id, serialize and let the controller deal with the rest. Knowing the form id will allow some exceptions to some forms, if needed. Each attempt has me banging my head on my desk.
Why are no forms being executed?
And if I get one form working, why isn't the other? [Similar code sample with '.change']
How do I get this ideal code to work across all the forms
OldCode:
JS
function doaction(){
alert("I work perfectly");
}
HTML
<form id='form_w'>
<input type='hidden' name="action" />
<input type='text' name="term"></input>
<input type='button' onclick="doaction()"/>
</form>
Ideal Code:
jQuery
//$('form.results').submit(function(e){ //DIDNT WORK
$('.rbutton').click(function(e){ // NOT WORKING EITHER
alert("This alert doesnt exist");
var form_id = e.target.id;
// gather data
// submit data via ajax
// update the dom by adding another tab/widget.
});
HTML
<form id='form_tab_id1' class="results">
<input type='hidden' name="A_action" />
<input type='text' name="term"></input>
<input type='button' class='rbutton'/>
</form>
<form id='form_tab_id2' class="results">
<input type='hidden' name="A_action" />
<input type='text' name="term"></input>
<input type='button' class='rbutton'/>
</form>
<form id='form_tab_id3' class="results">
<input type='hidden' name="B_action" />
<input type='text' name="term"></input>
<input type='button' class='rbutton'/>
</form>
Essentially, a user posted a solution. I am greatful he did. It pointed me in the right direction. [It was removed for whatever Reason that may be. But thanks George.]
His Solution was the following.
JQuery
$('.rbutton').click(function(){
var form = $(this).closest('form');
}
After juggling with so many variations, my code was drifting into an unstable code set. I honestly didn't know how to go about this; JQuery is prolly my sworn enemy. But knowing that the code George posted should be working, and wasn't, it kind of pointed me into other factors that I didn't consider. [I didn't take into consideration the code was being executed before the tabs with the '.rbutton' element were being populated.]
The Solution that helped me make this a more DRY principle was the following JQuery;
JQuery
$(document).on('click','.rbutton',function(){
var form = $(this).closest('form');
// Actions that are needed to be performed
}
Reason why this helps, or at least with my code, it binds this function to any element with the class '.rbutton' including new instances. As i mentioned above,these buttons were created after the jQuery was being executed; So nothing was being binded essentially. The following will do the binding to newly created elements, as if tho there was an active listener doing the additional binding over the document even after the code had been executed.
I'm only starting to dive into angular.js and have found this issue that I can't seem to get around. Consider this simple code:
<input type="text" ng-model="test">
<input type="text" value="{{test}}">
When I write in the first field, the second one is updated nicely. When I write in the second field and then go back to the first one, the binding is not updated anymore. Interestingly though, the HTML attribute value does get updated - it's just not displayed.
Equivalent (at least roughly) code in vanilla javascript does not suffer from this:
<input type="text" id="model">
<input type="text" id="binding">
<script>
var model = document.getElementById("model");
var binding = document.getElementById("binding");
model.addEventListener("keyup",function() {
binding.value = model.value;
});
</script>
Here's a fiddle for you to test both: http://jsfiddle.net/Q6b5k/
Any idea why this happens when using angular.js and how to fix this?
[EDIT] Judging by the initial replies, it appears I have not made it clear. I do not want the second field to update the first one. The binding is to be one-way only, e.g. to allow filtering or even manual corrections (such as automatic creation of a URL alias in a blog post creation form). http://jsfiddle.net/Q6b5k/1/
The value attribute is only used when rendering the initial HTML. After the page load, everything else happens in the Angular Event Loop and therefore you need to do something that event loop can pick up. You can use ng-change for what you are looking to do:
<input type="text" ng-model="test" ng-change="test2=test.toLowerCase();" />
<input type="text" ng-model="test2"">
This happens because {{value}} does not create a binding, it is used for interpolation.
The simplest solution is to use ng-model in both the fields
<div ng-app>
Angular.js:<br>
<input type="text" ng-model="test">
<input type="text" ng-model="test">
</div>
Demo: Fiddle
Here's the code for the form as it stands:
<form onsubmit="return false;" role="search" method="get" id="searchform" action="window.location.reload()" autocomplete="off">
<div><label class="screen-reader-text" for="s">Search for:</label>
<input type="text" value="" name="s" id="s" class="searchbar" >
</div>
</form>
Since I'm actually using a 'live search' plugin from wordpress (searches without navigating to another page), and it has a bug where deleting and re-entering the same text does not search again, I was wondering how I would get the page to reload if the user just pressed enter in the search box?
My second question is how to get the search bar to be highlighted or selected by default upon the page being loaded, just like Google? I've tried this:
<body onload"
$(function() {
$("input[name='s']").focus();
});
">
But it doesn't seem to do anything. Any help on either of these problems would really be appreciated!
You're not escaping the double quotes in the onload function. You can fix that by escaping the quotes with backslashes, but a better way to fix this is to put this code in a <script> tag (instead of inline):
<script>
$(function() {
$("input[name='s']").focus();
});
</script>
When using the $() function like this, it acts as a shortcut for $(document).ready(), so there's no need to attach it to the body's onload event.
Just to clarify, the other way to fix it would be to use escaped single quotes, like so:
<body onload"
$(function() {
$('input[name=\'s\']').focus();
});">
But I highly recommend you put this in a <script> tag. It's better not to use inline JavaScript, and with jQuery there is no need to.
Why is it that in a form that contains a Text Box and a Submit Button, I can Alert what has been typed in the text box by the user, but can't print it on the page? What am I doing wrong?
Here's the code
<form name="Serb" action="" method="get">
<input name="Name" type="text" size="15" maxlength="20" />
<input name="Join" type="submit" value="Join" onClick="serb(this.form)" />
<script type="text/javascript">
function serb(form){
var x = document.Serb.Name.value;
alert(x); \\this alerts
document.write(x); \\this should print on page
}
</script>
For some reason, the alert works fine and displays exactly what the user typed in the username box after pressing 'Join'. However, it won't print the information on the page. Why is that?
It does work. The value in the textbox is printed on the page.
BUT:
\\ do not mean anything in Javascript. Comments begin with //. This is most likely the reason why you are not seeing the value being written
document.write replaces whatever is in the HTML page with its argument. (If it is called after the document is loaded). So unless you are trying to learn Javascript this is not a very good idea.
Actually it is not a very good idea to use it even when learning Javascript, unless you are trying to learn how document.write works.
There are flexible (and better) ways to manipulate the content of a page, starting from the humble getElementById to complex DOM manipulation
It is not a good idea to use document.write() after the page has been loaded/parsed. At that point, it will overwrite the page HTML with new content. document.write() is generally used while the page is being loaded to insert content at a particular point into the page as it's being loaded.
If you want to put the value into some item on the page, then you need to use appropriate DOM methods for that, putting the value into an input field, setting the innerHTML on a div, etc...
You can read about document.write here: https://developer.mozilla.org/en/document.write.
Here's an example of fetching the value from the field and putting it in another object on the page without using document.write(): http://jsfiddle.net/jfriend00/dU8Sr/.
HTML:
<form name="Serb" action="" method="get">
<input name="Name" type="text" size="15" maxlength="20" />
<input name="Join" type="button" value="Join" onClick="serb(this.form)" />
</form>
<br>
<br>Output: <span id="output"></span>
Javascript:
function serb(form) {
var x = document.Serb.Name.value;
document.getElementById("output").innerHTML = x;
}
Is there a workaround for Internet Explorer to implement the functionality offered by 'this' javascript keyword to get the dom element that triggered the event?
My problem scenario is :
I have a variable number of text fields in the html form, like
<input type="text" id="11"/>
<input type="text" id="12"/>
..
I need to handle the "onchange" event for each text field, and the handling is dependent on the 'id' of the field that triggered the event.
So far I understand that my options are:
1) attach a dedicated event handler for each text field. so if I have n fields, i have n different functions, something like:
<input type="text" id="11" onchange="function11();"/>
<input type="text" id="12" onchange="function12();"/>
but the text fields are added and removed dynamically, so a better way would be to have one generic function instead.
2) use the 'this' keyword like:
<input type="text" id="11" onchange="functionGeneric(this);"/>
<input type="text" id="12" onchange="functionGeneric(this);"/>
But this option does not work with Internet Explorer.
Can anyone suggest a work around for getting it work in IE or some other solution that can be applied here?
Thanks.
I can't reproduce your problem. Here's an SSCCE based on the latest information in comments:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2618458</title>
<script>
function functionGeneric(id) {
alert(id); // Shows either 11 or 12 correctly.
}
</script>
</head>
<body>
<input type="text" id="text_11" onchange="functionGeneric(this.id.split('_')[1]);"/>
<input type="text" id="text_12" onchange="functionGeneric(this.id.split('_')[1]);"/>
</body>
</html>
It works fine in all major browsers I have here. Your actual problem lies somewhere else. Until you come up with more detail, or better, an SSCCE, it's shooting in the dark to the root cause.
The second option probably does not work because element IDs must start with alphabet or the underscore character (at least, according to the spec).
I would opt for something like this:
// make the ids start with a word, like "foo", followed by "_", followed by a number
$("input[id^='foo_']").change(function() {
doSomething(this.id.split("_")[1]); // extract the number, pass to function
});
That will attach a change handler to all of your inputs with IDs starting with 'foo', and split the number out of the ID to pass to the generic function which works on the number.