So today i have decided to learn javascript and try something that seem simple. . But i'm stuck and can't work out why this don't work.
I'm trying to copy the text from divs with same ids onclick to an input but it always copy's the first divs text into the input and not the div i clicked.
Any ideas how i could fix this?
function copyToInput(elementId) {
var getText = document.getElementById(elementId).innerText;
var chatHudInput = document.getElementsByClassName('hud-chat-input')[0];
chatHudInput.value = getText;
}
<div class="hud-chat-message" id="message" onclick="copyToInput('message');"> SOME TEXT HERE </div>
<hr>
<div class="hud-chat-message" id="message" onclick="copyToInput('message');"> SOME MORE TEXT HERE </div>
<hr>
<div class="hud-chat-message" id="message" onclick="copyToInput('message');"> EVEN MORE TEXT HERE </div>
<hr>
<input type="text" name="message" class="hud-chat-input" placeholder="Enter your chat message..." maxlength="140">
Never use same id for elements instead use same class
. You can pass the whole element in the onclick function and get its text in the function
function copyToInput(elementId) {
var chatHudInput = document.getElementsByClassName('hud-chat-input')[0];
chatHudInput.value = elementId.innerText;
}
<div class="hud-chat-message message" onclick="copyToInput(this);"> SOME TEXT HERE </div>
<hr>
<div class="hud-chat-message message" onclick="copyToInput(this);"> SOME MORE TEXT HERE </div>
<hr>
<div class="hud-chat-message message" onclick="copyToInput(this);"> EVEN MORE TEXT HERE </div>
<hr>
<input type="text" name="message" class="hud-chat-input" placeholder="Enter your chat message..." maxlength="140">
Two div's can not share an id. You can share class', however, but id's are unique identifiers.
https://www.w3schools.com/tags/att_id.asp
The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).
Try This:
function copyToInput(elementId) {
var getText = document.getElementById(elementId).innerText;
var chatHudInput = document.getElementsByClassName('hud-chat-input')[0];
chatHudInput.value = getText;
}
<div class="hud-chat-message" id="message" onclick="copyToInput('message');"> SOME TEXT HERE </div>
<hr>
<div class="hud-chat-message" id="message2" onclick="copyToInput('message2');"> SOME MORE TEXT HERE </div>
<hr>
<div class="hud-chat-message" id="message1" onclick="copyToInput('message1');"> EVEN MORE TEXT HERE </div>
<hr>
<input type="text" name="message" class="hud-chat-input" placeholder="Enter your chat message..." maxlength="140">
Use the following code. All your elements must have unique ID's. In your code, the only reason it uses the first one is because the first one it the one it would use (since you can only have 1 ID, and the code assumes you only have 1 ID). Just give the 3 elements different IDs.
function copyToInput(elementId) {
var getText = document.getElementById(elementId).innerText;
var chatHudInput = document.getElementsByClassName('hud-chat-input')[0];
chatHudInput.value = getText;
}
<div class="hud-chat-message" id="message1" onclick="copyToInput('message1');"> SOME TEXT HERE </div>
<hr>
<div class="hud-chat-message" id="message2" onclick="copyToInput('message2');"> SOME MORE TEXT HERE </div>
<hr>
<div class="hud-chat-message" id="message3" onclick="copyToInput('message3');"> EVEN MORE TEXT HERE </div>
<hr>
<input type="text" name="message" class="hud-chat-input" placeholder="Enter your chat message..." maxlength="140">
ID must be unique, in your case id is not unique so when document.getElementById(elementId) see first id that matchs message , takes it and does not continue to search( so get first div always).
your code does not require a ID, use of this. this refer to div that click on it.
function copyToInput(elementId) {
var chatHudInput = document.getElementsByClassName('hud-chat-input')[0];
chatHudInput.value = elementId.innerText ;
}
<div class="hud-chat-message" id="message" onclick="copyToInput(this);"> SOME TEXT HERE </div><hr>
<div class="hud-chat-message" id="message" onclick="copyToInput(this);"> SOME MORE TEXT HERE </div><hr>
<div class="hud-chat-message" id="message" onclick="copyToInput(this);"> EVEN MORE TEXT HERE </div><hr>
<input type="text" name="message" class="hud-chat-input" placeholder="Enter your chat message..." maxlength="140">
Related
I'm learning how to code js and one of my goals is to have a pseudo commenting system on my webpage. I'm wondering how to make javascript that can make it so that the user can type a comment and it'll display on the webpage. I've tried using getelementbyclassname but because I'm a beginner I don't really know what I'm doing.
HTML:
<div class="commentform">
<h1>Leave your comment!</h1>
<br>
<br>
<form class="commentform" method="post">
<p>Nickname or Name</p> <input id="name" required="required" type="text">
<br>
<p>Comments: </p><textarea id="comment" name="comments" rows="8" cols="20"></textarea>
<button type="button" name="commentsubmit">Comment!</button>
</form>
</div>
So you want the comment to pop up when the user submits the form. A problem I noticed about your code is that <button type="button" name="commentsubmit">Comment!</button> doesn't actually submit the form - it should have type="submit".
Also, you don't specify where on the webpage you want the comment to be placed, so I'll assume it's some div, I'll use <div id="target"></div> but it could be anything.
First: triggering JS when the form is submitted
You can use the .addEventListener function to call a function when the form is submitted. It seems like you are having some trouble selecting the form though. One way is to use document.querySelector, which is more versatile than getElementsByClassName, since you have more than one element with the same class name. We want to select a form with class commentform, which can be represented as form.commentform (look familiar? this is also a CSS selector!).
document.querySelector("form.commentform").addEventListener("submit", function(event) {
});
This selects the form, and adds a listener that triggers a function when the form is submitted. We can place code inside of this function body.
Second: putting the comment on the page
We'll need to retrieve the comment first. The comment is in a textarea with id="comment" - perfect, we can use document.getElementById("comment") to select it. Then, we can call .value on the textarea to retrieve its contents.
document.getElementById("comment").value
Then, we can set the contents of the <div id="target"></div> to the comment. This can be done the same way as we retrieved the textarea, except we use .innerText instead of .value.
document.getElementById("target").innerText = document.getElementById("comment").value;
This now sets the text of the target div to equal the comment that was entered. If you also want the page to not refresh when the user submits the form, you'll want to put event.preventDefault(); in the function as well, to tell the browser to prevent the default behavior of submitting a form (refreshing the page).
document.querySelector("form.commentform").addEventListener("submit", function(event) {
event.preventDefault();
document.getElementById("target").innerText = document.getElementById("comment").value;
});
<div class="commentform">
<h1>Leave your comment!</h1>
<br>
<br>
<form class="commentform" method="post">
<p>Nickname or Name</p> <input id="name" required="required" type="text">
<br>
<p>Comments: </p><textarea id="comment" name="comments" rows="8" cols="20"></textarea>
<button type="submit" name="commentsubmit">Comment!</button>
</form>
</div>
<div id="target"></div>
If you also want to display the nickname, the steps are similar. I'll leave that as an exercise for you.
All what you need to do is to add a script tag and within it make a function where you can get the value of what your're typing within the text field, add the onclick to the button so that you invoke the function.
<div class="commentform">
<h1>Leave your comment!</h1>
<br>
<br>
<form class="commentform" method="post">
<p>Nickname or Name</p> <input id="name" required="required" type="text">
<br>
<p>Comments: </p><textarea id="comment" name="comments" rows="8" cols="20"></textarea>
<button onclick='getText()' type="button" value="hello" name="commentsubmit">Comment!</button>
</form>
<p id = 'demo'> </p>
</div>
<script>
function getText (){
var x = document.getElementById("comment").value
document.getElementById("demo").innerHTML = "You commment is : " + x;
console.log(x)
}
</script>
You can do something like this....
const handleComment = (e)=>{
e.preventDefault();
const newDiv = document.createElement("div");
newDiv.innerText = e.target.comments.value;
const comments = document.getElementById("comments")
comments.append(newDiv)
}
const form = document.getElementById("commentForm")
form.addEventListener("submit", handleComment, true);
<div id="comments"></div>
<div class="commentform">
<h1>Leave your comment!</h1>
<br>
<br>
<form id="commentForm" class="commentform" >
<p>Nickname or Name</p> <input id="name" required="required" type="text">
<br>
<p>Comments: </p><textarea id="comment" name="comments" rows="8" cols="20"></textarea>
<button type="submit" name="commentsubmit">Comment!</button>
</form>
</div>
What I did was added an event listener to the form that captures the submit event.
I then took the comment text and used innerText to add it to a dynamically created div (using document.createElement).
Finally I appended the div to another div I created and gave an Id of comments.
(inside the HTML)
I can't seem to get the input value for "name", I have tried using .value in JS but when I run the code I get undefined.
HTML code
<div class="col-1">
<label for="fname">Name</label>
</div>
<div class="col-2">
<input type="text" id="fname" placeholder="Enter name" required>
</div>
<div class="col-3">
<button onClick="gather()" id="submitButton">submit</button>
</div
JS code
var submit = document.getElementById("submitButton");
submit.addEventListener("click",gather);
function gather(){
name = document.getElementById("fname");
message = "Thank you for subscribing "+name.value+ "!";
alert(message);
}
Just use var for create variable and all work.
var submit = document.getElementById("submitButton");
submit.addEventListener("click",gather);
function gather(){
var name = document.getElementById("fname");
var message = "Thank you for subscribing "+name.value+ "!";
alert(message);
}
<div class="col-1">
<label for="fname">Name</label>
</div>
<div class="col-2">
<input type="text" id="fname" placeholder="Enter name" required>
</div>
<div class="col-3">
<button onClick="gather()" id="submitButton">submit</button>
</div>
I suggest you to see this post:
Is var necessary when declaring Javascript variables?
you can simply do .value in the same line and get the value of the element
name = document.getElementById("fname").value;
console.log(name)
You must put all your codes into window.onload. This method running your code when all elements in page loaded. And this will solve your problem.
window.onload = () => {
//some js codes
}
I am trying to use jQuery to take the user input and insert it into multiple divs with the class of userInput. I was able to use vanilla JavaScript but i don't want to keep repeating my code using ID's.
So far i can take the user input and display it as an alert so i know its being read. So can i take this input from the input field and place it into a class?
<form>
<input class="userInput" type="text" maxlength="10" onclick="insertInput()" placeholder="Username" required><br>
<a href="#chapter-1">
<div id="submitbutton" class="button">Continue</div>
</a>
</form>
$(function() {
$("#submitbutton").click(function() {
alert($(".userInput").val());
});
});
$(function() {
$("#submitbutton").click(function() {
$('.userInput').text($(".userInput").val());
});
});
check this fiddle
Define number of divs having same class.Then just set the input value to class as text.
$(function() {
$("#submitbutton").click(function() {
var value = $(".userInput").val();
$(".insert").text(value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input class="userInput" type="text" maxlength="10" placeholder="Username" required><br>
<a href="#chapter-1">
<div id="submitbutton" class="button"> Continue</div>
</a>
</form>
<div class="insert">
</div>
<div class="insert">
</div>
<div class="insert">
</div>
Something like so:
var elements = document.querySelectorAll('p.userInput');
var doAction = function(event) {
var inputValue = document.querySelector('input.userInput').value;
for(var i=0; i < elements.length; i++) {
elements[i].innerHTML = inputValue;
}
}
var element = document.querySelector('#submitbutton');
element.addEventListener('click', doAction);
<form>
<input class="userInput" type="text" maxlength="10" placeholder="Username" required><br>
<a href="#chapter-1">
<div id="submitbutton" class="button"> Continue</div>
</a>
</form>
<p class="userInput"> </p>
<p class="userInput"> </p>
<p class="userInput"> </p>
No reason to use jQuery.
Goal: Enable the user to link form fields to specific locations in a content from a different div and then append the individual input fields' text to those specific locations respectively.
Here is the fiddle
HTML:
<form>
<div>
<label for="1">One:</label>
<input type="text" id="1" />
</div>
<div>
<label for="2">Two:</label>
<input type="email" id="2" />
</div>
<div>
<label for="3">Three:</label>
<input type="email" id="3" />
</div>
<div>
<label for="4">Four:</label>
<input type="email" id="4" />
</div>
<div>
<label for="5">Five:</label>
<input type="email" id="5" />
</div>
<div>
<label for="6">Six:</label>
<input type="email" id="6" />
</div>
<div>
<label for="7">Seven:</label>
<input type="email" id="7" />
</div>
</form>
<div class="text-area">
<p>asd</p>
<p>asd</p>
<p>asd</p>
<p>asd</p>
<p>asd</p>
<p>asd</p>
<p>asd</p>
</div>
Js:
function replaceText() {
var thisvalue = $(this).val();
var thisattr = $(this).siblings('label').attr('for');
//alert(thisvalue);
$('.text-area p').each(function(){
$(this).text(function () {
return $(this).text().replace("["+thisattr+"]", "["+thisvalue+"]");
});
});
}
In the fiddle, click on the text "asd", that will enable you to type anything. You will see, that once you enter a value in the input tag beside "One:", it replaces the text as required. What I could think of as of now, is, to type a "tag" that is enclosed between square brackets, and then the function compares the tag with the input's label attr "for" and replaces it with the input value. There is one major flaw to this: the user has to tag again and again for the same input every time they want to change the value, which renders the form useless because why won't they just type the information directly rather than using the form.
This comes close, if not identical, to the way stackoverflow itself creates the link tags, image tags etc in the text box when we type in here to ask questions.
The functionality you want to achieve is similar to Angular JS, where realtime update happens when you are typing in a text box.
If not, you can use oninput event. You can have a span tag or a placeholder next to your "Asd" and just replace your placeholder innertext with the text of the control
I have a form field that I am duplicating when one clicks on the "Add" button. When an ID is duplicated, I want to add an incremental number to it. My code below is appending a 0 to the end of each new ID instead of counting. So #mark-description becomes mark-description00 instead of #mark-description2. I've looked a couple other similar posts here but am unable to determine what I'm doing wrong. Any thoughts would be much appreciated.
NOTE: I'm using ids because a jQuery plugin I'm using requires them.
Javascript:
$('#add-character-button').on('click', function () {
var source = $('.mark:last'),
clone = source.clone();
var count = 0;
clone.find('.copyme').val($(this).attr('title')).attr('id', function(i, val) {
return val + count;
});
clone.insertAfter('.mark:last');
});
HTML:
<div>
<input class="checkbox" id="standard" name="mark-type" type="checkbox" value="Standard Character">
<label class="no-placeholder" for="standard-character"></label>
<div class="standard-mark-container">
<div class="mark" id="mark-details">
<div class="mark-name">
<label class="placeholder" for="mark-name"><span>text</span></label>
<input class="copyme" id="mark-name" name="mark-name" placeholder="" title="Enter your mark name" type="text">
</div>
<div class="description">
<label class="placeholder" for="mark-description"><span>text</span
</label>
<textarea class="copyme" id="mark-description" name="mark-description" placeholder="" title="Enter a description"></textarea>
</div>
<div class="remove"> <a class="remove-mark-button" href="#" id="remove-character-button"><span>Remove</span></a>
</div>
</div>
</div>
<div class="add-mark"><a class="add-mark-button" href="#" id="add-character-button"><span>+ Add</span></a></div>
</div>
You should probably not even be using id's on the items that you are cloning. And you SHOULD be using array access notation (i.e. mark-name[]) in your field names. Without this you are only going to get one of the duplicate fields with the same name posted.
Here is what I would suggest.
HTML:
<div>
<input class="checkbox" id="standard" name="mark-type" type="checkbox" value="Standard Character">
<label class="no-placeholder" for="standard-character"></label>
<div class="standard-mark-container">
<div class="mark">
<div class="mark-name">
<label class="placeholder"><span>text</span>
<input class="copyme" name="mark-name[]" placeholder="" title="Enter your mark name" type="text">
</label>
</div>
<div class="description">
<label class="placeholder"><span>text</span>
<textarea class="copyme" name="mark-description[]" placeholder="" title="Enter a description"></textarea>
</label>
</div>
<div class="remove"><a class="remove-mark-button" href="#"><span>Remove</span></a>
</div>
</div>
</div>
<div class="add-mark"><a class="add-mark-button" href="#" id="add-character-button"><span>+ Add</span></a></div>
</div>
javascript:
$('#add-character-button').on('click', function() {
// make clone
$template = $('.mark:last');
var $clone = $template.clone();
// set values to default in clone
$clone.find('.copyme').each(function() {
$(this).val($(this).attr('title'));
});
// insert into DOM
$clone.insertAfter($template);
});
$('.remove').on('click'), function() {
$(this).closest('.mark').remove();
});
This fully eliminates the need to modify id names and simplifies your code.
is this what you're looking for? i simplified the code so i wouldnt have to type all the ids and fors and stuff. http://jsfiddle.net/swm53ran/134/
$(document).ready(function() {
var count = 0;
$('.add').on('click', function() {
count++;
var clone = $('.template').clone('true').removeClass('template');
clone.find('textarea').attr('id', 'textarea' + count);
clone.find('textarea').html('Id: ' + clone.find('textarea').attr('id'));
clone.appendTo('.sections');
});
});
Add
<div class="sections">
<div class="template section">
<input type="checkbox" /><br/>
text <input type="text"/><br/>
textarea <textarea id="textarea">Id: textarea</textarea>
</div>
</div>
although, i would suggest not using id's, but if you're intent on using them, this should work for your purposes.