How to set span's text from text area on page load - javascript

I want to set the text in a span from a text area's value when the page has loaded.
I have a span:
<span id='message'></span>
I have a text area which I set the value for with a rails variable:
<%= f.text_area :text_message, value: #user.text_message, id: 'text_message' %>
When the page has loaded I want the span's text to be the same as the text areas text. Something like (which doesn't work):
(document).ready(function() {
var message_text = $("#text_message").value;
$("#message").html(message_text);
});

jquery object doesn't have the definition of value it is in javascript.
Use val() function for it.
var message_text = $("#text_message").val();
and you also forgot to use $with document object
$(document).ready(function() {
var message_text = $("#text_message").val()
$("#message").html(message_text);
});
Js Fiddle Demo

You are trying to use DOM object property value with jQuery object. You need to use val() instead of value. The value attribute could only be assessed with javascript DOM object but not with jQuery object.
Change
var message_text = $("#text_message").value
To
var message_text = $("#text_message").val();
OR, use indexer to convert the jQuery object to DOM object.
var message_text = $("#text_message")[0].value;

on dom ready use
$(document).ready(function() {
var message_text = $("#text_message").val();
$("#message").text(message_text);
});
$(document).ready(function() {
var message_text = $("#text_message").val();
$("#message").html(message_text);
});

You need to use text() or html() instead of .value to grab the content.
$(document).ready(function() {
var message_text = $("#text_message").text();
$("#message").html(message_text);
});
Working example

Use text() to set the text insted of html() DEMO
$(document).ready(function() {//$ is missing here
var message_text = $("#text_message").value
$("#message").text(message_text);
});
When ypu set the text the span wiil be for example0:
<span id="message">hi</span> //here hi is set as text

Related

Manipulate var in jquery by doing find and text

I use a WYSIWYG editor in my page. I collect the HTML in a callback function. I would like now change the content with jQuery. For that I do a find() to select the text I want to replace. Then I want to replace it, but I'm stuck!
$('.save').click(function() {
var html = $('#edit').editor('get_html');
console.log(html)
var ma_societe_OLD = $(html).find('.ma_societe').attr('data');
var ma_societe = $(html).find('.ma_societe').text();
if (ma_societe === ma_societe_OLD) {
$(html).find('.ma_societe').text('dfdsfsdfds');
}
console.log(html);
});
As you can see, I want to replace the content of the span with my own text. But it's not working.
The issue is because you're making amendments to the jQuery object, but you never store those changes anywhere. You either create a new jQuery object containing the original, unchanged html, or return the html string directly.
Instead, create $(html) in a variable, make your changes to it, then work with it as needed. Something like this:
$('.save').click(function() {
var html = $('#edit').editor('get_html');
var $html = $(html);
var $maSociete = $html.find('.ma_societe')
if ($maSociete.text() === $maSociete.attr('data')) {
$maSociete.text('dfdsfsdfds');
}
var result = $html[0].outerHTML
console.log(result);
});

Attach event to a dynamically created dom element

In the code below I'm dynamically creating different posts.
Each post has its own image.
$(function () {
for(post in data){
//get from the data post details
var titleData = data[post]["title"];
var descriptionData = data[post]["description"];
var imageData = "images/"+data[post]["image"];
//create elements with jquery
var postHolder = $('<div class="post row"></div>');
var img = $('<img src="'+imageData+'" data-title="'+titleData+'" class="col-sm-3 img-post">');
var textHolder = $('<div class="col-sm-9"></div>');
var title = $('<h4 class="title-post"></h4>').append(titleData);
var description = $('<p class="explanation-post"></p>').append(descriptionData);
textHolder.append(title);
textHolder.append(description);
postHolder.append(img);
postHolder.append(textHolder);
$('.posts-container').append(postHolder);
img.on('click',function(){alert(this.data-title);});
}
});
I want that when I click the image, it will alert the title of the post (what's known as "titleData") and that the "textHolder" will change his background color to grey.
The limitation on this challenge are:
To pass a different parameter as the "titleData" each time.
To use minimum space in the memory.
data-title is invalid identifier in JavaScript. To access the data-* attributes, You can use HTMLElement.dataset
alert(this.dataset.title)
OR, As you are using jQuery .data() method.
alert($(this).data("title"));
What is in the alert is wrong.
You are saying
this.data MINUS title
You sould be using bracket notation if the name has a dash in it.
alert(this["data-title"]);
or better with getAttribute
alert(this.getAttribute("data-title"));
or jQuery
alert($(this).data("title"));
alert($(this).attr("data-title"));
so the final code with the bg color change should be
img.on('click', function() {
alert($(this).attr("data-title"));
textHolder.css("background-color","#CCC");
console.log(textHolder.css("background-color"))
});

JQuery replace html element contents if ID begins with prefix

I am looking to move or copy the contents of an HTML element. This has been asked before and I can get innerHTML() or Jquery's html() method to work, but I am trying to automate it.
If an element's ID begins with 'rep_', replace the contents of the element after the underscore.
So,
<div id="rep_target">
Hello World.
</div>
would replace:
<div id="target">
Hrm it doesn't seem to work..
</div>​
I've tried:
$(document).ready(function() {
$('[id^="rep_"]').html(function() {
$(this).replaceAll($(this).replace('rep_', ''));
});
});​
-and-
$(document).ready(function() {
$('[id^="rep_"]').each(function() {
$(this).replace('rep_', '').html($(this));
});
​});​
Neither seem to work, however, this does work, only manual:
var target = document.getElementById('rep_target').innerHTML;
document.getElementById('target').innerHTML = target;
Related, but this is only text.
JQuery replace all text for element containing string in id
You have two basic options for the first part: replace with an HTML string, or replace with actual elements.
Option #1: HTML
$('#target').html($('#rep_target').html());
Option #2: Elements
$('#target').empty().append($('#rep_target').children());
If you have no preference, the latter option is better, as the browser won't have to re-construct all the DOM bits (whenever the browser turns HTML in to elements, it takes work and thus affects performance; option #2 avoids that work by not making the browser create any new elements).
That should cover replacing the insides. You also want to change the ID of the element, and that has only one way (that I know)
var $this = $(this)
$this.attr($this.attr('id').replace('rep_', ''));
So, putting it all together, something like:
$('[id^="rep_"]').each(function() {
var $this = $(this)
// Get the ID without the "rep_" part
var nonRepId = $this.attr('id').replace('rep_', '');
// Clear the nonRep element, then add all of the rep element's children to it
$('#' + nonRepId).empty().append($this.children());
// Alternatively you could also do:
// $('#' + nonRepId).html($this.html());
// Change the ID
$this.attr(nonRepId);
// If you're done with with the repId element, you may want to delete it:
// $this.remove();
});
should do the trick. Hope that helps.
Get the id using the attr method, remove the prefix, create a selector from it, get the HTML code from the element, and return it from the function:
$('[id^="rep_"]').html(function() {
var id = $(this).attr('id');
id = id.replace('rep_', '');
var selector = '#' + id;
return $(selector).html();
});
Or simply:
$('[id^="rep_"]').html(function() {
return $('#' + $(this).attr('id').replace('rep_', '')).html();
});
From my question, my understanding is that you want to replace the id by removing the re-_ prefix and then change the content of that div. This script will do that.
$(document).ready(function() {
var items= $('[id^="rep_"]');
$.each(items,function(){
var item=$(this);
var currentid=item.attr("id");
var newId= currentid.substring(4,currentid.length);
item.attr("id",newId).html("This does not work");
alert("newid : "+newId);
});
});
Working Sample : http://jsfiddle.net/eh3RL/13/

How to reference an id with brackets in jQuery

I'm painfully new to jQuery and I need to grab the value on change of a text input box with an id of id[2][t] and display that text in a div to be styled later on (also styled with jQuery).
This is the input box code:
<input id="id[2][t]" name="id[2][t]" maxlength="20" type="text">
This is the div I am trying to display it in:
<div id="textpreview"></div>
This is what I have tried, among other variation with no success:
$(document).ready(function() {
$('#id\\[2\\]\\[t\\]').change(function() {
var txtval = $('#id\\[2\\]\\[t\\]').text();
$("#textpreview").val(txtval);
});
});
I know the brackets are a problem but they need to remain for other reasons.
Any ideas?
$( document.getElementById( "id[2][t]" ) ).change( function(){
$( "#textpreview" ).text( this.value );
} );
You might consider revising your IDs (though I'm guessing they might be auto-generated). According to this question your IDs are invalid against the spec
Use the attribute selector instead:
var sel = $("[id='id[2][t]']");
sel.change(function() {
$("#textpreview").val(sel.text());
});
Plain Old JavaScript:
var elem = document.getElementById('id[2][t]');
elem.onchange = function()
{
var elem = document.getElementById('textpreview');
elem.removeChild(elem.firstChild)
elem.appendChild(document.createTextNode(this.value));
}
Ahhh... now doesn't that feel better?
You have val and text backwards. Swap them:
$('#id\\[2\\]\\[t\\]').change(function() {
var txtval = $('#id\\[2\\]\\[t\\]').val();
$("#textpreview").text(txtval);
});
val is used to get the value of the textbox. text to set the text within the div.
You can further simplify the code by using this instead of re-querying the element.
$('#id\\[2\\]\\[t\\]').change(function() {
var txtval = this.value;
$("#textpreview").text(txtval);
});
You can try using the attribute selector instead of the id selector.
$('[id="id[2][t]"]')

Replace text with HTML element

How can I replace a specific text with HTML objects?
example:
var text = "some text to replace here.... text text text";
var element = $('<img src="image">').event().something...
function ReplaceWithObject(textSource, textToReplace, objectToReplace);
So I want to get this:
"some text to replace < img src...etc >.... text text text"
And I would like manipulate the object element without call again $() method.
UPDATE:
I solved.
thanx #kasdega, i made a new script based in your script, because in your script i can't modify the "element" after replace.
This is the script:
$(document).ready(function() {
var text = "some text to replace here.... text text text";
var element = $('<img />');
text = text.split('here');
$('.result').append(text[0],element,text[1]);
$(element).attr('src','http://bit.ly/mtUXZZ');
$(element).width(100);
});
I didnt know that append method accept multiples elements.
That is the idea, only need to automate for multiple replacements
thanx to all, and here the jsfiddle
do a split on the text you want to replace then use the array indexes 0 and 1...something like:
function ReplaceWithObject(textSource, textToReplace, objectToReplace) {
var strings = textSource.split(textToReplace);
if(strings.length >= 2) {
return strings[0] + objectToReplace.outerHTML() + strings[1];
}
return "";
}
UPDATE: I found another SO post Get selected element's outer HTML that pointed me to a tiny jquery plugin that helps here.
I believe this jsfiddle has what you want. outerHTML is the tiny jquery plugin I included in the JSFiddle.
You can also use replace which will reduce some code: http://jsfiddle.net/kasdega/MxRma/1/
function ReplaceWithObject(textSource, textToReplace, objectToReplace) {
return textSource.replace(textToReplace, objectToReplace.outerHTML());
}
function textToObj (text,obj,$src){
var className = "placeholder-"+text;
$src.html($src.html().replace(text,"<div class='"+className+"'></div>"));
$("."+className).replace(obj);
}
you can use $(selector).outerHtml to get the html string of an element
You can replace the html directly: http://jsfiddle.net/rkw79/qNFKF/
$(selector).html(function(i,o) {
return o.replace('old_html','new_html');
})

Categories

Resources