I'm a jquery newbie
If I have a fieldset like this, how can I add new attributes like class="error" and also modify the text of the legend from the script?
I do not know anything about the fieldset or the legend apart from the fact that they exist
<fieldSet>
<legend>My Legend</legend>
<script type="text/javascript">
//I want to select the legend???
</script>
</fieldset>
To add the class:
$('fieldset').addClass('error');
To modify the legend text:
$('fieldset legend').html('New Legend');
However you need know more information about the fieldset, if you have more then on the page, because the code above will modify all the fieldset tags on it.
From your example above the following would change the text of the 'legend' element and add a class to it -
$("fieldSet legend").text('New Text').addClass('newClass')
You might need to change the $("fieldSet legend") part of the code depending on what other elements you ultimately display on your page.
EDIT
If you want to refer to a specific fieldset you could do something like this to change the first fieldset on the page -
$("body fieldSet:first-child legend").text('New Text').addClass('newClass')
Otherwise you'd need to add a class or id to the fieldset. So if your fieldset looked like this -
<fieldSet class="chosen">
Your jQuery would need to be -
$("fieldSet.chosen legend").text('New Text').addClass('newClass')
Or if you add an id -
<fieldSet id="chosen">
jQuery -
$("#chosen").text('New Text').addClass('newClass')
There exists workaround for this one.
<fieldSet>
<legend>My Legend 1</legend>
<script type="text/javascript">
var to = 'New Legend 1';
var id = "temp" + Math.floor(Math.random()*100000);
document.write('<span id="'+id+'"></span>');
var temp = $('#'+id); scriptParent = temp.parent(); temp.remove();
scriptParent.find('legend').html(to);
</script>
</fieldset>
<fieldSet>
<legend>My Legend 2</legend>
<script type="text/javascript">
var to = 'New Legend 2';
var id = "temp" + Math.floor(Math.random()*100000);
document.write('<span id="'+id+'"></span>');
var temp = $('#'+id); scriptParent = temp.parent(); temp.remove();
scriptParent.find('legend').html(to);
</script>
</fieldset>
All SCRIPT elements are evaluated in order as the document is loaded. So, when you use document.write inside inline SCRIPT element, the write accours right next to SCRIPT. Generating unique element after script, and referencing it, could be traced by DOM with ease. You can eaven try creating function for such an action. Just play with it, and I hope, you will understand :)
Try jQAPI for jQuery references if you are new to jQuery.
Have you tried the following expression?
$("legend").html();
Related
Is there a way to get document property values into html script in text area.
for example:
I have a drop down which have values like "google","yahoo","Facebook"
and my html script may be like
< SpotfireControl id="a23e53a498af447294614ec708f50ede" /> A href="http://www.Document propety value.com/">.
So if you select google in drop down ,the above html script will change to
< SpotfireControl id="a23e53a498af447294614ec708f50ede" /> A href="http://www.google.com/">
I want to see this dropdown and link in one text area.
much appreciated
If your tag is as follows:
<a id="mylink" href="">
Then you can set the href like so:
document.getElementById("mylink").href = "https://google.com";
If your select has an id="myselect", you can get the value like so:
document.getElementById("myselect").value
Now you can set your link:
var site = document.getElementById("myselect").value;
document.getElementById("mylink").href = "https://"+site+".com";
Now, you want this to happen when you change the drop-down (select) option, so you'll need to add an event listener for when it changes.
document.getElementById("myselect").addEventListener("change",
function() {
var site = document.getElementById("myselect").value;
document.getElementById("mylink").href = "https://"+site+".com";
}
}
Do note that your event listener can only be added after the selector and the link have loaded (so the code needs to be afterwards). If you've never used JavaScript before, you should note that you need <script type="text/javascript"> and </script> tags to enclose it.
How to get the html of element itself using Jquery html. In the below code I would like get the input element inside div using JQuery as shwon below
<div id="content">content div</div>
<input type='text' id="scheduledDate" class="datetime" />
$(function() {
console.log($('#scheduledDate').html('dsadasdasd'));
$('#content').html($('#scheduledDate').html());
});
EDIT:
Can I get the $("#scheduledDate") as string which represent the real html code of the input box, because my final requirement is I want to pass it to some other SubView( I am using backboneJS) and eventually use that html code in a dust file.
My original requirement was to get that input field as string so that I can pass it to some other function. I know, if I keep it inside a DIV or some other container, I can get the html by using .html method of JQuery. I dont want use some other for that purpose. I am just trying to get html content of the input box itself using it's id.
If you want to move the input element into div, try this:
$('#content').append($('#scheduledDate'));
If you want to copy the input element into div, try this:
$('#content').append($('#scheduledDate').clone());
Note: after move or copy element, the event listener may need be registered again.
$(function() {
var content = $('#content');
var scheduledDate = $('#scheduledDate');
content.empty();
content.append(scheduledDate.clone());
});
As the original author has stated that they explicitly want the html of the input:
$(function() {
var scheduledDate = $('#scheduledDate').clone();
var temporaryElement = $('<div></div>');
var scheduleDateAsString = temporaryElement.append(scheduledDate).html();
// do what you want with the html such as log it
console.log(scheduleDateAsString);
// or store it back into #content
$('#content').empty().append(scheduleDateAsString);
});
Is how I would implement this. See below for a working example:
https://jsfiddle.net/wzy168xy/2/
A plain or pure JavaScript method, can do better...
scheduledDate.outerHTML //HTML5
or calling by
document.getElementById("scheduledDate").outerHTML //HTML4.01 -FF.
should do/return the same, e.g.:
>> '<input id="scheduledDate" type="text" value="" calss="datetime">'
if this, is what you are asking for
fiddle
p.s.: what do you mean by "calss" ? :-)
This can be done the following ways:
1.Input box moved to the div and the div content remains along with the added input
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
$("#content").append($inputBox);
});
2.The div is replaced with the copy of the input box(as nnn pointed out)
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
var $clonedInputBox = $("#scheduledDate").clone();
$("#content").html($clonedInputBox);
});
Div is replaced by the original input box
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
$("#content").html($inputBox);
});
https://jsfiddle.net/atg5m6ym/4485/
EDIT 1:
to get the input html as string inside the div itself use this
$("#scheduledDate").prop('outerHTML')
This will give the input objects html as string
Check this js fiddle and tell if this is what you need
https://jsfiddle.net/atg5m6ym/4496/
I have a requirement where I need to set html input tags ids with js variables.
example:
<input type='text' id='(here I need js variable)'/>
I know there's a way to do that by creating entire element by
document.createElement('div name');
and I can append to the div, but I want it in a simple way.
If it is a Java variable then I can do it like
<%String myVar = "txtId"%>
<input type='text' id='<%= myVar%>'/>
Is there any simplest way to put a js variable in a html tag?
Update :
Thanks for the answers guys, I know we can create any number of input elements and append to the parent element. And also we could get an element by tag name and can set id for those elements.But my question is, is there a way to use(or) place (or) insert a js variable in html tag just like we could insert a java variable in the html tag as I've shown above.
like,
<script>
var txtId = 'txt1';
</script>
<html>
<input type='text' id='document.write(txtId)'/>
</html>
Is there a way to do like this?
Assign ids to exist element , if you want to use java variable as your new id, you can use jstl tag like this
var inputs = document.getElementsByTagName("input");
for(var i = 0 ; i<inputs.length ; i++){
inputs[i].id = "newIdWhatYouWant";
}
<input type='text' class="name"/>
you can use attr() jQuery function and set any string you like. so in action:
var str="newId"
$('name_or_#id_or_.class').attr('id',str)
Can you use something like this ?
<script>
var a = "some_id";
document.write("<input type='text' id='"+a+"' />");
</script>
http://jsfiddle.net/9DAE4/
I think this will help you.
If you face any problem then tell me.
OR
You can create whole control dynamically and set all data see this link.
It's very helpful.
I have tried this one, you will have existing ID then only you can change it's ID :
<script type="text/javascript">
function addName()
{
var k ='add';
document.getElementById('txttt').id = k;
//document.getElementById('two').value = 'hi'
var srchdata = document.getElementById(k).id;
alert(srchdata);
}
</script>
<body onload="addName()">
If your data is dynamic then some problem can be arise.
I have used alert to display new ID of textbox.
If you want some other way then tell me how ?
And what problem can be arise in this ?
My first SO question! Here's what I am trying to do:
I'm rewriting a tool that generates some code a user can paste directly into Craigslist and other classified ad posting websites. I have created a list of websites (they populate from a database with PHP) the user can choose from with a radio button, and I want their choice to populate as bare text (not a link) between some <p></p> elements in a textarea. I'm using jQuery for this.
Textarea before the user chooses:
<p id="thing"></p>
Textarea after the user chooses:
<p id="thing">www.somewebsite.com</p>
HTML
<input type="radio" name="sitechoice" value="www.websiteone.com">www.websiteone.com<br />
<input type="radio" name="sitechoice" value="www.secondwebs.com">www.secondwebs.com
<textarea>
Some stuff already in here
Here is the website you chose:
<p id="thing"></p>
More stuff already here.
</textarea>
JS
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val();
alert(website);
$("#thing2").html(website);
});
});
JS Fiddle (With comments)
If you see the JS Fiddle, you can see that I put another p element on the page outside the textarea, and it updates just fine, but the one inside the textarea does not. I have read many other like questions on SO and I'm starting to think that I can't change an element that's between textarea tags, I can only change the entire textarea itself. Please, lead me to enlightenment!
You actually can fairly easily manipulate the text contents of the textarea like it is part of the DOM, by transforming its contents into a jQuery object.
Here is a jsFiddle demonstrating this solution: http://jsfiddle.net/YxtH4/2/
The relevant code, inside the input change event:
// Your normal code
var website = $(this).val();
$("#thing2").html(website);
// This turns the textarea's val into a jQuery object ...
// And inserts it into an empty div that is created
var textareaHtml = $('<div>' + $("#textarea").val() + '</div>');
// Here you can do your normal selectors
textareaHtml.find("#thing").html(website);
// And this sets the textarea's content to the empty div's content
$("#textarea").val(textareaHtml.html());
The empty div wrapping your HTML is so that you can easily retrieve it as a string later using jQuery's .html() method, and so the parse does not fail if additional text is entered around the p element inside the textarea.
The real magic is $($("#textarea").val()), which takes your textarea's text and parses it into an HTML node contained in a jQuery object.
It can't do it the way that you are thinking (i.e., manipulate it as if it were a DOM element), but it is still accessible as the value of the textarea, so you can retrieve it like that, use basic string manipulation to alter it, and then set the updated string as the new value of the textarea again.
Something like this . . . first give the <textarea> an id value:
<textarea id="taTarget">
Some stuff already in here
Here is the website you chose:
<p id="thing"></p>
More stuff already here.
</textarea>
Then alter your script like this:
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val();
var currentTAVal = $("#taTarget").val();
$("#taTarget").val(currentTAVal.replace(/(<p id="thing">)([^<]*)(<\/p>)/, "$1" + website + "$3"));
});
});
Unless you need the <p> element in there, you might consider using a more simple placeholder, since it won't actually act as an HTML element within the textarea. :)
EDIT : Fixed a typo in the .replace() regex.
I know that this answer is a little bit late, but here it goes =)
You can do exactly the way you want to do. But for that, you need to implement a small trick.
by having this HTML
<input type="radio" name="sitechoice" value="www.websiteone.com">www.websiteone.com
<br />
<input type="radio" name="sitechoice" value="www.secondwebs.com">www.secondwebs.com
<p id="thing2"></p>
<textarea id="textarea">
<p id="thing"></p>
</textarea>
you can edit textarea content, as a DOM by implementing something like the function changeInnerText
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val(); // Gets value of input
changeInnerText(website);
//$("#thing").html(website); // Changes
//$("#thing2").html(website); // Does not change
});
var changeInnerText = function(text) {
var v = $("#textarea").val();
var span = $("<span>");
span.html(v);
var obj = span.find("#thing")[0];
$(obj).html(text);
console.log(obj);
console.log(span.html());
$("#textarea").val(span.html());
}
});
As you can see, I just get the information from the textarea, I create a temporary variable span to place textarea's content. and then manipulate it as DOM.
Instead of attempting to insert the text into the <p> element, insert the text into <textarea> element and include the <p> tag. Something like this should do the trick:
Change:
$("#thing").html(website);
to:
$("textarea").html('<p id="thing">'+website+'</p>');
And here is a fiddle: http://jsfiddle.net/nR94s/
I have several vertically stacks divs and I want to have a div appear when I click a button within each of these divs. The div that I want to appear will be the exact same for each appearance with the exception of an id associating it with the outer div. How do I do this in Javascript?
I assume I should use the createElement() within Javascript, but how do I append it to the end of a specific element. Also, when creating an element, I have to hardcode the html in the Javascript file. Is there anyway to leave the element within the html design file. I want to seperate design from code as much as possible.
Clone Node
var clone = myDiv.cloneNode();
Example (live demo):
HTML
<div>
<input type="button" onclick="functionClone(this);" value="Dolly"/>
<input type="button" onclick="functionClone(this);" value="Dolly_1"/>
</div>
Javascript:
functionClone = function(subject){
var clonenode = subject.cloneNode(true);
subject.value = subject.value + '\'s been cloned!';
subject.disabled = true;
insertElementAfter(subject, clonenode);
}
insertElementAfter = function(subject, newElement){
subject.parentNode.insertBefore(newElement,subject.nextSibling);
}
To append an element below your div use this:
subject.parentNode.appendChild(clonenode)