Possible to pass a value from HTML to javascript? - javascript

I have searched SO but i didnt really understand the answers related to this question and they were all related to JSP so im not sure if it applies to my usage.
I have a list of comments on a page and when a user click on "reply" the javascript code is executed, but the javascript function which is running needs to know which comment it is going to be working on in order to insert the reply form in the correct div. I have information about which comment im working on in the html code but i need to be able to access this information also in the external JS file.
Is there a way to send this information from html to javascript ?

[updated]
You can use data attribute of Jquery
See an example:
http://jsfiddle.net/9AJUJ/2/
html
<div id="div1"></div>
<button class="mydiv" data-info="1" >button 1</button>
<div id="div2"></div>
<button class="mydiv" data-info="2" >button 2</button>
js
//when document is load
$(function(){
$(".mydiv").click(function(){
$("#div" + $(this).data('info')).append('hello');
});
})

Asume this is your HTML code :
<article>
<header>
Posted by XYZ
</header>
<p>
This is a comment...
</p>
<footer>
<button type="button">
Reply
</buttuon>
</footer>
</article>
Here the JQuery code :
$(function() {
$('article>footer>button[type="button"]').click(function(){
$(this).parent().parent().append(/** HERE IS WHAT YOU APPEND **/);
});
});

Does each reply button have an ID that matches the comment ID? That would allow you to know which button was pressed (this.id or this.name) and would correspond to the related comments field.
your input would be
<input type="text" id="comments1">
and your button would be
<button type="button" id="button1">Click Me!</button>
in your button js you can do something like
var buttonID = this.id;
var commentID = 'comments' + buttonID.substring(6);
var commentObj = document.getElementById(commentID);

You need to edit the markup of the reply buttons.
<button class="reply-button" data-commentid="42">Reply</button>
<!-- ^ Add this attribute -->
In your event listener:
var commentId = this.dataset.commentid;

What I have done (so I don't know if it is the right way to do this), is I have create my html code by a php class and give and and id to each div like "div number" + "answers".
So my page htmml looks like:
<div id="0answers">
<h1 id="0title"> </h1>
<p id="0p"> </p>
</div>
<div id="1answers">
<h1 id="1title"> </h1>
<p id="1p"> </p>
</div>
<div id="2answers">
<h1 id="2title"> </h1>
<p id="2p"> </p>
</div>
And so have all the information you need for exemple modify the title n° 5 when someone click on the div n°3.
Is that that need?

So...
var i = 0;
var button = document.getElementById(i + 'button');
while(button){
var p = document.getElementById(i + 'p');
// and do what you want
++i;
var button = document.getElementById(i + 'button');
}

Related

How can I set multiple ckeditors of same class even if we add new ckeditor by appending on click a button?

I am planning to use multiple ckeditors on a single page. I need to append ckeditor on click a button but it's not working on the appended ckeditor.
I have tried to insert the same class and call all ckeditors like "querySelectorAll('.editor')"
It's working properly on every '.editor' class. But my problem is with the ckeditor appended after clicking a button.
I found the '.editor' class has added by inspecting the source code. I think It will work, Now I need help.
<div class="editors">
<div class="editor">
<p>Editor 1 here</p>
</div>
<div class="editor">
<p>Editor 2 here</p>
</div>
</div>
<button class="add-editor">Add New Editor</button>
<script>
$('.add-editor').click(function(){
$('.editors').append(' <div class="editor"><p>Editor 3 here (Editor Not Loading here)</p></div>')
});
var allEditors = document.querySelectorAll('.editor');
for (var i = 0; i < allEditors.length; ++i) {
InlineEditor.create(allEditors[i]);
}
</script>
The trick here is that you only want to enable CKEditor to new editors. If you do it to existing ones, you'll get errors. You could solve that by adding an .enabled class to them, and that way, when you add a new one, you won't affect old ones.
// Once on page load, for existing editors
$(document).ready(enableEditors);
// When you click on the button
$('.add-editor').click(function() {
var count = $('.editor').length + 1;
$('.editors').append('<div class="editor"><p>Editor ' + count + ' here</p></div>');
enableEditors();
});
function enableEditors() {
$('.editor:not(.enabled)').ckeditor().addClass('.enabled');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.ckeditor.com/4.11.1/standard/ckeditor.js"></script>
<script src="https://cdn.ckeditor.com/4.11.1/standard/adapters/jquery.js"></script>
<div class="editors">
<div class="editor">
<p>Editor 1 here</p>
</div>
<div class="editor">
<p>Editor 2 here</p>
</div>
</div>
<button class="add-editor">Add New Editor</button>
You need to call CKEDITOR.replace('editor'); after creating the dynamic content to setup CKEDITOR on it.
Let me know if this isn't what you were hoping for.
N.B. Not sure why it's throwing an error, despite working. If anyone knows please let me know and I'll update the answer.
Demo
// Create click event for add button
$("#add-input").click(function() {
// Add new input to #input-list
$("#input-list").append('<input name="editor">');
// Replace newly added editor with CKEDITOR
CKEDITOR.replace('editor');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.ckeditor.com/4.11.1/standard/ckeditor.js"></script>
<button id="add-input">Add editor</button>
<div id="input-list"></div>

Select only the text inside div of sibling with class name, having many families of same class names

I wanted to copy the texts when the copy button is clicked. But, it copies the last(3rd) paragraph text when pressing any of the three buttons. It suppose to find previous sibling and copy that text when that particular button is clicked.
Here's my code. I think, I went wrong in the sibling thing. Let me know what I did wrong here:
//finding text to copy
$(document).ready(function(){
$(document).on('click', '.phc-hashtags-box-button', function () {
$(this).closest('.phc-hashtags-box').find('.phc-hashtags-box-tags');
copy = copy +$(this).text();
});
});
function copyToClipboard(element) {
var $temp = $('<input>');
$('body').append($temp);
$temp.val($(element).text()).select();
document.execCommand('copy');
$temp.remove();
}
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="phc-home-hashtags">
<div class="container">
<div class="phc-hashtags-box">
<h3 class="phc-hashtags-box-title">Dog1</h3>
<p class="phc-hashtags-box-tags">#dog #dogstagram #instadog #dogsofinstagram #worldofdogs #dogslove #cutedog #doggy #igdogs #dogs #pet #dogoftheday #myfriend #doglover #ilovemydog #ilovedog #doglove #doglife #mydog #happydog #1st</p>
<button onclick="copyToClipboard('.phc-hashtags-box-tags')" class="phc-hashtags-box-button">Copy</button>
</div>
<div class="phc-hashtags-box">
<h3 class="phc-hashtags-box-title">Dog2</h3>
<p class="phc-hashtags-box-tags">#dog #dogstagram #instadog #dogsofinstagram #worldofdogs #dogslove #cutedog #doggy #igdogs #dogs #pet #dogoftheday #myfriend #doglover #ilovemydog #ilovedog #doglove #doglife #mydog #happydog #2nd</p>
<button onclick="copyToClipboard('.phc-hashtags-box-tags')" class="phc-hashtags-box-button">Copy</button>
</div>
<div class="phc-hashtags-box">
<h3 class="phc-hashtags-box-title">Dog3</h3>
<p class="phc-hashtags-box-tags">#dog #dogstagram #instadog #dogsofinstagram #worldofdogs #dogslove #cutedog #doggy #igdogs #dogs #pet #dogoftheday #myfriend #doglover #ilovemydog #ilovedog #doglove #doglife #mydog #happydog #3rd</p>
<button onclick="copyToClipboard('.phc-hashtags-box-tags')" class="phc-hashtags-box-button">Copy</button>
</div>
</div>
</div>
</body>
</html>
Instead of picking by class which gets all of the element with that class, limit your find to the parent() div of the button and it will only get the relevant text:
$(document).ready(function(){
$(document).on('click', '.phc-hashtags-box-button', function () {
$(this).parent().find('.phc-hashtags-box-tags'); // notice the change on this line.
copy = copy +$(this).text();
});
});
EDIT:
Working solution:
Now i noticed - you are not passing a single element to copyToClipboard.
<button onclick="copyToClipboard('.phc-hashtags-box-tags')" class="phc-hashtags-box-button">Copy</button>
is sending the saving to copy the last element from 3 found with this. Try instead:
<button onclick="copyToClipboard($(this).parent())" class="phc-hashtags-box-button">Copy</button>
I believe that when you pass '.phc-hashtags-box-tags' to the onclick attr of the button elements, it is matching all of the elements with that class and returning the last match for the value of your function.
Instead, try changing the button onclick handler to:
copyToClipboard($this)
That said, the execCommand function is not working in the provided snippet so verifying is difficult.
Perhaps try passing IDs or try to architect a more elegant solution. So many relative jQuery selectors will inevitably cause bugs as complexity grows.

Creating buttons that display buttons

I am trying to make an online questionnaire that will only show the next question after answering the current question. I am very new at this and trying to learn as I go. How do I make the 2nd set of buttons appear only when you answer yes to question 1?
<html>
Question 1
<p>
<button onclick="myFunction1()">Yes</button>
<script>
function myFunction1() {
document.getElementById("demo").innerHTML = "Yes on question 1, display question 2";document.getElementById("demo").style.color = "black";}
</script>
<button onclick="myFunction2()">No</button>
<script>
function myFunction2() { document.getElementById("demo").innerHTML ="No on question 1 negative answer to question 1 display negative response";document.getElementById("demo").style.color = "red";}
</script>
</html>
<p id="demo"></p>
</script>
</p></p></p>
</html>
<head>
<script>
function showImg() {
document.getElementById("map_img").style.display = "";
}
</script>
</head>
<body>
<button onclick="myFunction3()">Yes</button>
<script>
function myFunction3() { document.getElementById("demo2").innerHTML = "Yes to question 2";}</script>
</html>
<button onclick="myFunction4()">No</button>
<script>
function myFunction4() {
document.getElementById("demo2").innerHTML = "No to question 2";}
</script>
</body>
<p id="demo2"></p>
Use css display: none; to hide the second question, then when the user clicks the yes button, you change it to display:block;
Here is an example: https://jsfiddle.net/mrpbtbgy/2/
document.querySelector("#q1Btn").addEventListener("click",()=>{
document.querySelector("#question2").style.display="block";
});
In my opinion, you have to put your second, third and ... questions into div's tags with style="display:none"
When the users click on the Yes button, you can easily change the display to block and show the next question.
Another thing is that your html is not formatted well.
Here is an example of html.
<html>
<head>
</head>
<body>
<div>Your first question</div>
<div style="display:none" id="question2">Your second question</div>
<script>
You can put all your functions here
</script>
</body>
</html>
I did a very simple example for you, you can check on the following link:
https://jsfiddle.net/L7gp4c5g/
Hope to help you!
Put the what you want to hide in a div hidden:
<div id="question2" style="visibility: hidden">
<button onclick="onClick(2)">Yes</button>
<button onclick="onClick(2)">no</button>
</div>
Use javascript to programmatically hide or show next div:
<script>
function onClick(button) {
document.getElementById('question' + (button + 1)).style.visibility = "visible"
}
</script>
As other I would have said :
If you want to get the results at the end of all the questions. (if user leave, you won't get nothing.)
A solution would be to put each question in hidden divs, on the same page, displaying them after each validation. This way you won't need to put and remove content. Example:
function showquestion(number){
$("#question"+number).removeClass("hidden"); // Show the next question
$("#question"+(number-1)).addClass("hidden"); // Hide the current question
}
.hidden{display:none;
visibility : hidden;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="question1" class=""> Mauvaise réponse</div>
<div id="question1" class=""> Question 1 <button type="button" onclick="showquestion(0)">yes</button><button type="button" onclick="showquestion(2)">No</button></div>
<div id="question2" class="hidden"> Question 2 <button type="button" onclick="showquestion(0)">yes</button><button type="button" onclick="showquestion(3)">no</button></div>
<div id="question3" class="hidden"> Question 3 <button type="button" onclick="showquestion(0)">yes</button><button type="button" onclick="showquestion(4)">no</button></div>
But we forgot the "yes / no" part, nor talk about the visibility of the question solution inside the source code.
The correct way of doing this would be an ajax call on each question validation : The user send the response to a php script, this script validate the response, or not, then send the content that will be inserted on the user page.
It's the only way for the user don't cheat, and it allow you to save his response on each step (if you save something).

How to create many toggle in runtime?

I created a page that displays post with comments using ajax
To view the comments user must click comment button correspond to the post
For simple understanding, example:
In HTML
Block
<button id="btn1">cmt1</button>
<button id="btn2">cmt2</button>
<div id="cmt1">comments</div>
<div id="cmt2">comments</div>
'
I tried of using for loop as
for(var i=0;i<count;i++){
$("#cmt"+i).hide();
$("#cmtbtn"+i).click(function(){
$("#cmt"+i).toggle('slow');
});
}
But It works well for the last cmtbtn only and whenever i click all other buttons last comment box only displays
I'm saying that is there is a way of for loop or any looping
Update: My Js file is here http://jsfiddle.net/9ss50nzc
Try to give a same and unique class to all "Comment Button" and also to "Comment Div". Like example bellow :
<button id="btn1" class="comtbtn"> cmt1 </button>
<button id="btn2" class="comtbtn"> cmt2 </button>
<div id="cmt1" class="comt-div">comments1</div>
<div id="cmt2" class="comt-div">comments2</div>
Then catch the click event on class "comtbtn" . Bellow is the js script to hide show of comment -
$('.comtbtn').click(function() {
var btnId = $(this).attr("id");
var id = btnId.slice(-1);
$( "#cmt"+id ).toggle( "slow" );
});
Add css to hide all the comment section when initially loaded to the DOM.
.comt-div{
display:none;
}
Is this the sort of thing you want? A means of getting the index of the button which is equivalent to the indexed position of the hidden comment on your document?
You just hide the previous comment and display the new comment.
var oldNode = '';
function showComment = function(index) {
if (typeof oldNode != undefined) $(oldNode).hide('slow');
$('.comment:eq('+$(index).index()+')').show();
oldNode = $('comment:eq('+$(index).index()+')');
}
<button onclick="showComment(this)">cmnt 1</button>
<button onclick="showComment(this)" >cmnt 2</button>
<div class='comment' style='display: none'>comment a</div>
<div class='comment' style='display: none'>comment b</div>
Start with giving your buttons and divs classes
<button id="btn1" class="actionButtons">cmt1</button>
<button id="btn2" class="actionButtons">cmt2</button>
<div id="cmt1" class="actionDivs" style="display:none">comments1<br/>more comments<br/>and even more</div>
<div id="cmt2" class="actionDivs" style="display:none">comments2<br/>another comment<br/>and another one</div>
Then loop through elements with that class name
for(var i = 0; i < $(".actionButtons").length; i++){
$(".actionButtons")[i].onclick = function () {
for(var j = 0; j < $(".actionDivs").length; j++){
if ($(".actionDivs")[j].id == this.innerText)
$("#" + this.innerText).show();
else
$("#" + $(".actionDivs")[j].id).hide();
}
};
}
Fiddle
I hope this takes you closer to your solution.
I got the answer it is possible to toggle inside loop by using traversing. Thanks everyone finally I sort out the answer.

How to replace html button with plain text

How do you replace a button with whatever words were on the button before? I was looking at an answer to another similar question, which said to use something like:
var myBtn = document.getElementById("buttonId"),
mySpan = document.createElement("span");
mySpan.innerHTML = myBtn.innerHTML ;
myBtn .parentNode.replaceChild(mySpan, myBtn);
but that had made what other buttons do change. Does anyone know another way to change a button to regular text?
I know that that code works just by itself, but it doesn't work with my code for some reason, so I don't really care what's wrong with that code. I'm just wondering if anyone knows another way to do it.
Thanks
<!DOCTYPE html>
<head>
<title></title>
</head>
<body>
<div id="myDiv">
<input type="button" value="Change into Text" id="submit" onClick="change()"> <!--button input that will trigger an event named change-->
</div>
</body>
</html>
<script type="text/javascript">
function change(){ //function to run when you click on the button...
var buttonValue = document.getElementById("submit").value; //stores the button value
document.getElementById("myDiv").innerHTML = buttonValue; // displays the value as a plain text inside "myDiv" - removing the button input entirely
}
</script>
EDIT:
I've just noticed you had multiple buttons in your page, which will make my previous example wrong. heres something that will make you work easier i think in case you will add extra buttons:
first heres the code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<ul>
<li id="id_1"><input type="button" value="Change into Text" onClick="change(1)" id="button_1"></li>
<li id="id_2"><input type="button" value="Change into Text" onClick="change(2)" id="button_2"></li>
<li id="id_3"><input type="button" value="Change into Text" onClick="change(3)" id="button_3"></li>
</ul>
</body>
</html>
<script type="text/javascript">
var id;
function change(id){
var buttonValue = document.getElementById("button_"+id).value;
document.getElementById("id_"+id).innerHTML = buttonValue;
}
</script>
In the HTML part, you can create a list (li) of buttons if that's your layout...
each list will have its own id, in this case id_x that will be used later when you replace its content. each button calls a function change(id) while id is just a unique number for each button.
In the JS part, the change(id) gets the id of the button that was clicked, takes its value, and replaces the innerHTML (content) of the relative list items with a plain text.
Let me know if you still need any other help.
Seems that you are looking for another way to replace the buttons with plain text, well I'll show you the jQuery way.
HTML
<div>
<button id="btn1" class="change-button">A button with some text 1</button>
<button id="btn2" class="change-button">A button with some text 2</button>
<button id="btn3" class="change-button">A button with some text 3</button>
</div>
jQuery
// When we click a button with a "change-button" class
$(".change-button").on("click", function(event){
// First we get the ID value of the clicked button
// example: "btn2"
var buttonId = $(this).attr('id');
// Then we get the html value of the clicked button
// example: "A button with some text 2"
var buttonText = $(this).html();
// We use the function replaceWith, to replace the button to a <span>
// with the buttonText variable we have
$('#' + buttonId).replaceWith("<span>" + buttonText + "</span>");
});
As you can see, it's a lot more cleaner with jQuery. You should try it!
Here is the fiddle so you can test it.
<html>
<script>
function fun()
{
var a = document.getElementById("hello").value;
document.getElementById("ad").innerHTML = a;
}
</script>
<body>
<div id="ad">
<input type="button" value="hello" id="hello" onClick="fun()">
</div>
</body>
</html>
sorry, edited the wrong post

Categories

Resources