Data only to click the div - javascript

Good morning, everyone.
I have a doubt. I have a list of div. textarea with text inside it and inside. text for a button event. Want to get only the data from the textarea div that the person clicking the button.
I would be very grateful for the help. thanks
Example code.
<div class="text">
<textarea id="texts" class="texts" rows="5" cols="45" name="textarea"> </ textarea>
<div class="bt" id="1234556">
<div class="button"> Send </div>
</div>
</div>

$('.button').click(function() {
var text = $('#texts').val();
// do something with text
alert(text);
});
Working demo at http://jsfiddle.net/PPcxm/

As long as you have the same structure (and presuming you have more than one example on the page as the button is a class and textarea is an id, the following would work:
$(".button").click(function()
{
var text = $(this).parent().prev().val();
});

Since you have a list of div.text your best bet is to query based upon the structure of your DOM.
$(".button").click(function() {
var $textArea = $(this).parents(".text").find(".texts");
//Do something with $textArea.Val();
});
What we simply do is call .parents() on the current div.button which will allow us to get the div.text element. From there you can simply find your textarea.texts element and get the corresponding value.
Code example on jsfiddle.

Related

Javascript: How to print input to <div> selected by class?

Edit: Thanks for the helpful answers so far! I'm still struggling to print the input to the "right" div, though. What am I missing?
Next to the input field, there is an option to select either "left" or "right". Depending on the selection, the input is to be printed eiether left or right on the click of a button. This is what I have - but it only prints to the left, no matter the selection.
jQuery(document).ready(function(){
$('.button').click(function(){
$('.input').val();
if ($('select').val() == "left"){
$('div.left').html($('.input').val());
}
else {
$('div.right').html($('.input').val());
}
});
});
</script>
Sorry if this is very basic - I am completely new to JS and jQuery.
I'm trying to print input from a form into a div. This is part of the source HTML modify (it's for a university class):
<input type="text" class="input">
<div class="left">
</div>
<div class="right">
</div>
Basically, text is entered into the field, and I need to print this text either to the "left" or the "right" div when a button is clicked.
So far, I have only ever dealt with divs that had IDs, so I used
document.getElementById("divId").innerHTML = ($('.input').val());
But what do I do now when I don't have an ID? Unfortunately, changes to the HTML source are not an option.
Thanks in advance!
Just use normal selectors, like css and jQuery does.
https://api.jquery.com/category/selectors/
in your case:
$('div.left').html($('.input').val());
As you see there are many ways to do this. You can get elements by tag name, class, id...
But the most powerful way is to get it with querySelector
function save() {
var input = document.querySelector('input').value;
document.querySelector('div.left').innerHTML = input;
}
<input type="text" class="input">
<button onclick="save()">Save</button>
<div class="left"></div>
<div class="right"></div>
There are plenty of other ways to target HTML elements, but the one you're looking for in this case is getElementsByTagName(). Note that this returns a NodeList collection of elements, so you'll additionally need to specify the index that you wish to target (starting at 0). For example, if you want to target the second <div> element, you can use document.getElementsByTagName("div")[1].
This can be seen in the following example:
let input = document.getElementsByTagName("input")[0];
let button = document.getElementsByTagName("button")[0];
let div2 = document.getElementsByTagName("div")[1];
button.addEventListener("click", function(){
div2.innerHTML = input.value;
});
<input type="text">
<button>Output</button>
<br /><br />
<div>Output:</div>
<div></div>
Since you have unique class names for each element, document.getElementsByClassName can be used. This will return an array of elements containing the class. Since you only have one element with each class name, the first element of the returned array will be your target.
<input type="text" class="input">
<button onclick="save()">Save</button>
<div class="left"></div>
<div class="right"></div>
<script>
function save() {
var input = document.getElementsByClassName('input')[0].value;
document.getElementsByClassName('left')[0].innerHTML = input;
}
</script>
This is one of the many ways to do what you want:-
Write the following in console:
document.getElementsByTagName("div");
now you can see the total number of div elements used in your current document/page.
You can select one of your choice to work on by using "index number"(as in array index) for that particular div.
Lets say your div having class name = "right" is the 3rd one among the other div elements in your document.
This will be used to access that div element.
document.getElementsByTagName("right")[2].innerHTML = "whatever you want to write";

Javascript get HTML of selected text nodes

I got the following HTML:
<div id="editable_phrase">
<span data-id="42">My</span>
<span data-id="43">very</span>
<span data-id="1">first</span>
<span data-id="21">phrase</span>
</div>
and I need to get the data-id attributes when I select (highlight) with a mouse these words. I use the following code:
var data = window.getSelection().getRangeAt(0).cloneContents();//this gets the data for all selected words
console.log(data);
It works fine except that when I select last word phrase, it selects only text without html contents. Any ideas how to fix that? I can use jQuery.
If I select 2 or 3 words, I need to get their data-ids respectively to each word, as it is with getRangeAt(0).cloneContents(). The problem is only with the last word, which does not return HTML code.
Thank you.
EDIT:
There has been a similar thread before, here is a working solution:
https://jsfiddle.net/hallleron/wg1pbwbf/2/
Basically you loop through the siblings in the selection to get each value and then parse the array as string to display it in my result paragraph for better visuals.
ORIGINAL:
If you want a jQuery-free version, here is a fiddle: https://jsfiddle.net/hallleron/wg1pbwbf/
The whole Javascript Part is the following:
document.getElementById('editable_phrase').addEventListener("click", getDataId);
function getDataId(){
console.log(window.getSelection().anchorNode.parentElement.attributes[0].nodeValue);
}
So every time the event listener detects a click, it gets the selected text/span and extracts its data-id attribute from the object.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="editable_phrase">
<span data-id="42">My</span>
<span data-id="43">very</span>
<span data-id="1">first</span>
<span data-id="21">phrase</span>
</div>
<script>
$('#editable_phrase').on('click','span',function(){
var res = $(this).attr('data-id');
alert(res);
})
</script>

Closest() in jQuery doesn't work when at the same level

Problem:
I want (after clicking on a button - this part is OK) to select the closest element with a class .my-textarea, but the using of prev() is not always possible, because the code is dynamic. Could you help?
Details:
I have this HTML code:
<div class="row">
<div class="label">Description:</div>
<textarea class="my-textarea" name="my-textarea" rows="8" cols="40"></textarea>
<button type="button" class="my-submit" name="my-submit">Save</button>
</div>
And my JS code (in on button with class "my-submit" click event) is:
var text = $(this).closest('.my-textarea').val();
But it's not working. I am getting undefined.
If I tried:-
var text = $(this).prev().val();
I will get the text of the text-area, but as I've mentioned, my code is dynamic and the order and number of elements will change. So, prev() is out of option.
Any idea how to make closest() work?
I always select parent and than search for child with class. That way your element can be placed virtually anywhere in parent.
$(this).parent().find('.my-textarea').val();
Need to Use siblings() instead of closest():-
$('.my-submit').click(function(e){
e.preventDefault();
var text = $(this).siblings('textarea').val();
console.log(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="label">Description:</div>
<textarea class="my-textarea" name="my-textarea" rows="8" cols="40"></textarea>
<button type="button" class="my-submit" name="my-submit">Save</button>
</div>
You need to refer it using class
closest will traverse up the DOM tree to look for the element, while in this case textarea is sibling of the button.
$('.my-submit').click(function(){
var text = $(this).siblings('.my-textarea').val();
alert(text)
})
DEMO

Selectively getting text from <div>

<div class="myDiv">
<p>I need get<strong>this</strong>
<a title="And this" href="#">but not this</a>
</p>
<p>And also<strong>This</strong>
<a title="And this" href="#">but not this</a>
</p>
</div>
How do I grab everything in p tag except for the text in nested a tag. And also I need to get values for "title" attirbute for tag a?
Using http://api.jquery.com/replaceWith/
Creates a clone
Replaces the a tags with their title attributes
Calls text() on the cloned node
http://jsfiddle.net/mendesjuan/cBejv/2/
var clone = $('.myDiv p').clone();
clone.find('a').replaceWith(function() {
return this.getAttribute('title');
})
console.log(clone.text());
Outputs
I need get this
And this And also This
And this
How about this:
$('.myDiv a').text('');
$('.myDiv p').each(function() {
console.log($(this).text()+$('a',this).attr('title'));
});
jsFiddle example.
Something like this would work. There may be a much better way to do this, but this was the first thing to come to mind.
var $clone = $('.myDiv').clone();
$clone.find('a').remove();
$('#output').append($clone.text());​
Make sure you add an element with id="output" to see the results.

How to replace an element by textarea using javascript

What I am making is basically is a user profile that has a text box for description added by the user about himself/herself. Although I have a separate page where the user can edit the profile, but I want to provide a feature that when a user hovers over his description box then he sees an edit button.
If the user clicks that button, then he/she can edit the description field there itself, and the backend will be updated using Ajax. The ajax call and the backend processing is simple, but how can I replace the html with a textarea and submit button and again put back the original html using javascript.
Here is what my html look like
<div id="personalText" >
edit
<p id="descText">{{profile.desc}}</p>
</div>
When somebody clicks editButton I want to replace the html inside personalText with a textarea containing the original text in descText, and an update button. And when the user edits the text and click update, I will update the backend model and again put the <a> tag and the <p> tag.
Can anybody help. I seem to know how to do parts of it, but can't figure out how I will replace the original structure on update click.
Instead of creating/destroying DOM elements an option would be to have the edit <textarea/> hidden.
<div id="personalText" >
<div class="display">
edit
<p id="descText">{{profile.desc}}</p>
</div>
<div class="edit" style="display:none;">
<input type="submit" value="Update"/>
<textarea>{{profile.desc}}</textarea>
</div>
</div>
Then your jQuery can simply toggle the elements and handle your ajax post.
$("input[type='submit']").on("click", function() {
$.ajax({
url:"/your/url/"
}).success(function(){
$(".display, .edit").toggle();
$("#descText").html($("textarea").val());
});
return false;
});
Example on jsfiddle
$('#editButton').click(function(){
var text = $('descText').text();
var textArea = $('<textarea></textarea>');
textArea.value = text;
$('#personalText').replaceWith(textArea);
});

Categories