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

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";

Related

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

Trying to target an element if it has a label

Attempted to log a label to console via
var labelTest = document.getElementById('js_8').label;
console.log(labelTest);
However it is returning undefined.
Edit: correcting some stuff, sorry at work and trying to do this in between other tasks. What my end result needs to be is targeting the inner html of the js_8 ID, but with React it is different for each of the Pages that it is on. So I want to add an extra stipulatoin of having that label attribute.
HTML:
<span data-reactroot="" label="1715724762040702" class="_xd6" data-pitloot-persistonclick="true" display="inline" data-hover="tooltip" data-tooltip-content="Copy Text to Clipboard" id="js_8"><div class="_xd7">1715724762040702</div></span>
I'm not sure exactly what you're after, but this is a way to connect a <label> and <input> together via JavaScript.
var some_id = 'someid',
my_label = getLabel(some_id);
function getLabel(id) {
return document.querySelector('[for=' + id + ']')
}
my_label.click();
<label for='someid'>My Label</label>
<input type='text' id='someid' />
You can associate a <label> with an <input>, <output>, <select> or <textarea> element in one of two ways:
The for attribute:
<label for="js_8">Test</label>
<input id="js_8">
Or by wrapping the element with a label:
<label>Test<input id="js_8"></label>
You can then access the associated label(s) as an array like this:
var labelsTest = document.getElementById('js_8').labels;
// labelsTest will be an array of 0 or more HTMLLabelElement objects
console.log(labelsTest);
Label-able elements can have more than one label.
So essentially I believe I am going to want to utilize var x = getAttribute("label") . The fact that the attribute was titled label confused me, and in turn I goof'd.

Populate a hidden form field using the div of a drop menu (drop down menu is created using divs not select, option etc)

I have a form.
Please note I must use divs for creating the form drop down and not the select option method etc. It just has to be done that way. The code is below.
<form action="url.asp" method="get">
<div class="search-button"><i class="fa fa-search"></i><input type="submit" /></div>
<div class="search-drop-down">
<div class="title"><span>Choose Category</span><i class="fa fa-angle-down"></i></div>
<div class="list">
<div class="overflow">
<div class="category-entry" id="Category1">Category One</div>
<div class="category-entry" id="Category2">Category Two</div>
</div>
</div>
</div>
<div class="search-field"><input type="text" name="search-for" id="search-for" value="" placeholder="Search for a product" /></div>
<input type="hidden" id="ChosenCategory" name="ChosenCategory" value="CATEGORY1 OR CATEGORY2 (WHICHEVER SELECTED)" />
</form>
As shown in the code above I need to populate the hidden field value as per the chosen option which the user selects in the drop down.
I have used about 20 different variations of getElementById or onFocus functions but cannot get it to work.
The only thing I can get to work is the following JavaScript and it just populates the hidden field value with the first id ignoring completely which one has actually been selected(clicked) by the user;
var div = document.getElementById('DivID');
var hidden = document.getElementById('ChosenCategory');
hidden.value = div.innerHTML;
I'm running classic asp so if there is a vbscript way then great, otherwise if I have to use JavaScript to do it then as long as it does the job I'll be happy still.
A click handler on the options could be used to update the value.
No jQuery or any other external library is needed. Below is a working example. Of course, in your case the input element could be of type hidden, but I made it text here for the sake of demonstration.
//Add the click handlers
var options = document.getElementsByClassName('option');
var i = 0;
for (i = 0; i < options.length; i++) {
options[i].addEventListener('click', selectOption);
}
function selectOption(e) {
console.log(e.target);
document.getElementById('output').value = e.target.id;
}
div {
padding: 10px;
}
div.option {
background-color: #CCC;
margin: 5px;
cursor: pointer;
}
<div>
<div class="option" id="Category1">Category One</div>
<div class="option" id="Category2">Category Two</div>
</div>
<input type="text" id="output" />
You should be able to achieve what you're after with a fairly simple setup involving listening for clicks on two separate <div> elements, and then updating an <input> based on those clicks.
TL;DR:
I've put together a jsfiddle here of what it sounds like you're trying to make work: https://jsfiddle.net/e479pcew/5/
Long version:
Imagine we have 2 basic elements:
A dropdown, containing two options
An input
Here's what it might look like in HTML:
<div class="dropdown">
<div id="option-one">Option 1</div>
<div id="option-two">Option 2</div>
</div>
<input type="text" id="hidden-input">
The JavaScript needed to wire these elements up should be fairly easy, but let me know if it doesn't make sense! I've renamed things throughout to make things as explicit as possible, but hopefully that doesn't throw you off.
One quick thing - this is an incredibly 'naive' implementation of this idea which has a lot of potential for refactoring! However I just wanted to show in the most basic terms how to use JavaScript to make this stuff happen.
So here we go - first things first, let's find all those elements we need. We need to assign variables for the two different dropdown options, and the hidden input:
var optionOne = document.getElementById("option-one");
var optionTwo = document.getElementById("option-two");
var hiddenInput = document.getElementById("hidden-input");
Cool. Next we need to make a function that will come in handy later. This function expects a click event as an argument. From that click event, it looks at the id of the element that was clicked, and assigns that id as a value to our hiddenInput:
function valueToInput(event) {
hiddenInput.value = event.target.id;
}
Great - last thing, let's start listening for the clicks on specific elements, and if we hear any, we'll fire the above valueToInput function:
optionOne.addEventListener("click", valueToInput, false);
optionTwo.addEventListener("click", valueToInput, false);
That should get you going! Have a look at the jsfiddle I already linked to and see if it makes sense - get in touch if not.
Are you allowed to use JQuery in this project? It would make your life a lot easier. You can detect when a div is clicked and populate the hidden field.
This could do it:
$(document).ready(function() {
$('.category-entry').click(function() {
$('#ChosenCategory').val($(this).text()); }); });

How to pick out classes that start with a particular string

This might be hard to explain, but I need a way to loop through a bunch of elements I've already selected and for each one find classes that start with the word "icon". So for example I might have the following elements
<div class="button iconStar"></div>
<div class="button iconPlus"></div>
<div class="button iconLeft"></div>
<div class="button iconRight"></div>
<div class="button iconUp"></div>
<div class="button iconDown"></div>
So, I begin by selecting the elements and looping through them....
$(".button").each(function(){
// Some code here
});
Now, I could put the following code in the loop...
if ($(this).hasClass("iconStar")){
$(this).append("<IMG SRC='Images/star.gif'>");
}
I would then have to repeat that for each possible icon, which seems very inefficient.
What I'd like to do in the "each" loop is just cycle through all the classes that $(this) has and pick out the one that begins with ICON and then use that to append the image.
Can anyone help?
I recommend against using classes if you're not going to associate the class with the image. (which would be the most correct way) What I would do instead is put a link to the image in the rel tag.
This does what you want, and will still validate as valid css.
<div class="button" rel="images/star.jpg">iconStar</div>
<div class="button" rel="images/plus.jpg">iconPlus</div>
<div class="button" rel="images/left.jpg">iconLeft</div>
<div class="button" rel="images/right.jpg">iconRight</div>
<div class="button" rel="images/up.jpg">iconUp</div>
<div class="button" rel="images/down.jpg">iconDown</div>
<script>
$('.button').each(function() {
$(this).append("<img src='"+$(this).attr('rel')+"'>");
});
</script>
See the example here: http://jsbin.com/acasu
Note, if you're using a lot of tiny images, you're going to want to use CSS Sprites. As it will greatly improve the performance of your page.
If you absolute had to do it the way you are suggesting, you could do the following:
$(".button[class^='button icon']").each(function() {
var iconSrc = $(this).attr('class').substr("button icon".length)
$(this).append("<img src='/images/"+iconSrc+".jpg'>");
});
For each element, get the value of the class attribute, split it by ' ', take the second part and call the image.
From the top of my head
$(".button[class^='button icon']").each(function (el) {
classStr = el.className;
classes = classStr.split(' ');
image = 'images/' + classes[1] + '.jpg';
});
Not entirely sure of the syntax, bit rusty!
Try using this selector:
$(".button[class^='button icon']")
This should select only elements that have the class button, and also have a class that start with 'icon'.
Of course, this selector also assumes that your CSS class always begins with "button" first and not "icon".

Categories