Button value set in editable div when click on - javascript

I am using button tag <button value="1">1</button>
Basically I want when this button is pressed, the value of the button is set into editable div.
<div contentEditable='true'; >Value from button</div>
Is that possible with client side script?

Try the below code: (EDIT Modified as user has subsequently indicated that he will use this to create a calculator)
We are doing the following:
Assign an onclick function to the button. This will be called whenever the button is clicked.
An ID is added to both the button tag and the div tag to access them using the getElementById method in JavaScript.
this.value will pass the value of the button that is currently clicked to the function.
Inside the JavaScript, we get the value of the button and set it to the innerHTML of the required div. Note: Since += is used, it would take the current contents of the div and append the button's value to it (like, if 1 is pressed followed by 2, the div would have 12 as its content).
HTML
<button value="1" id='btn1' onclick='setBtnValue(this.value);'>1</button>
<button value="2" id='btn2' onclick='setBtnValue(this.value);'>2</button>
<div contentEditable='true' id='div1'></div>
Javascript
function setBtnValue(btnVal){
document.getElementById('div1').innerHTML += btnVal;
}
Demo

you can use getElementById method.
<button value="1" onclick="function1(this)">1</button>
<div contentEditable='true' id='edit'>value from button</div>
<script type='text/javascript'>
function function1(obj){
document.getElementById("edit").innerHTML=obj.value;
}
</script>

Yes this is possible but you have to assign the id.
<button onclick="put()" id="but" value="1">1</button>
<div id="pol" >Value from button</div>
Now with function use
function put()
{
document.getElementById("pol").innerHTML = document.getElementById("but").value;
}
DEMO

HTML:
<button value="1" class="button">1</button>
<button value="2" class="button">2</button>
<div contentEditable="true" id="element"></div>
JS:
var buttons = document.getElementsByClassName('button');
var div = document.getElementById('element');
for(var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function(event) {
div.innerHTML = event.target.value;
});
}
Working example.

Related

JQuery Detect Which File Upload Button Clicked [duplicate]

How to detect which dynamic button is clicked?
Note: The #dCalc Element is added dynamically...
<!-- STATIC -->
<div id="dBlock">
<!-- ADDED DYNAMICALLY -->
<div id="dCalc">
<input id="firstNumber" type="text" maxlength="3" />
<input id="secondNumber" type="text" maxlength="3" />
<input id="btn1" type="button" value="Add" />
<input id="btn2" type="button" value="Subtract" />
<input id="btn3" type="button" value="Multiply" />
<input id="btn4" type="button" value="Divide" />
</div>
</div>
$("input").click(function(e){
var idClicked = e.target.id;
});
$(function() {
$('input[type="button"]').click(function() { alert('You clicked button with ID:' + this.id); });
});
Since the block is added dynamically you could try:
jQuery( document).delegate( "#dCalc input[type='button']", "click",
function(e){
var inputId = this.id;
console.log( inputId );
}
);
demo http://jsfiddle.net/yDNWc/
jQuery can be bound to an individual input/button, or to all of the buttons in your form. Once a button is clicked, it will return the object of that button clicked. From there you can check attributes such as value...
$('#dCalc input[type="button"]').click(function(e) {
// 'this' Returns the button clicked:
// <input id="btn1" type="button" value="Add">
// You can bling this to get the jQuery object of the button clicked
// e.g.: $(this).attr('id'); to get the ID: #btn1
console.log(this);
// Returns the click event object of the button clicked.
console.log(e);
});
Detect event on dynamically created elements
Two examples, jQuery and vanilla JavaScript ahead:
jQuery
Use the .on() method with delegated events, which follows this syntax:
$("staticParentSelector").on("eventName", "dynamicChildSelector", handlerFn);
Example:
// Assign event listeners to dynamic child elements
// Will work for either existent elements or inserted in the future
$("#dBlock").on("click", '[type="button"]', (evt) => {
const staticParent = evt.delegateTarget; // This is #dBlock
const dynamicChild = evt.currentTarget; // This is the dynamic child
console.log(`Static Parent ID is: ${staticParent.id}`)
console.log(`Dynamic child ID is: ${dynamicChild.id}`)
});
<!-- STATIC -->
<div id="dBlock">
<!-- ADDED DYNAMICALLY -->
<div id="dCalc">
<button type="button" id="btn1">Add</button>
<button type="button" id="btn2">Subtract</button>
<button type="button" id="btn3">Multiply</button>
<button type="button" id="btn4">Divide</button>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
JavaScript
The same in vanilla JavaScript can be achieved like the following, with the difference in that JS has no notion of delegateTarget (which is a jQuery property on their proprietary Event object) therefore the slight modification:
// Assign event listeners to dynamic child elements
// Will work for either existent elements or inserted in the future
document.querySelector("#dBlock").addEventListener("click", (evt) => {
const staticParent = evt.currentTarget; // This is #dBlock
const dynamicChild = evt.target.closest('[type="button"]'); // This is the dynamic child
if (!dynamicChild) return; // Do nothing (no designated dynamic child is clicked)
console.log(`Static Parent ID is: ${staticParent.id}`)
console.log(`Dynamic child ID is: ${dynamicChild.id}`)
});
<!-- STATIC -->
<div id="dBlock">
<!-- ADDED DYNAMICALLY -->
<div id="dCalc">
<button type="button" id="btn1">Add</button>
<button type="button" id="btn2">Subtract</button>
<button type="button" id="btn3">Multiply</button>
<button type="button" id="btn4">Divide</button>
</div>
</div>
as you can see neither of the above implementations stick solely on the Event.target Element per-se, for the reason that if we had i.e. an icon inside the buttons (like: <button id="add" type="button">Add <i class="icon-plus"></i></button>) and if a click landed on the icon directly, the Event.target would end up being the icon, not the Button Element - and we might miss to retrieve the needed data, like the specific button ID etc, resulting in a broken app logic.

How to change text of buttons after clicking on them for multiple buttons?

I am using multiple buttons and my problem is when i am clicking on any button then the text changes of first button, but not that button on which i am clicking. I am using here same button id for all buttons but it is hard to use different button id's for such multiple buttons so what is any other simple way without using different id's.
I want to change only one button at a time on which i am clicking but not other buttons. PLEASE HELP..!
html code
user1
<input type="button" value="Connect" id="toggle" onclick="myFunction()">
user2
<input type="button" value="Connect" id="toggle" onclick="myFunction()">
user3
<input type="button" value="Connect" id="toggle" onclick="myFunction()">
and so on...
and js function is
function myFunction()
{
var change = document.getElementById("toggle");
if (change.value=="Connected") change.value = "Connect";
else change.value = "Connected";
}
You can do it like this as well? You can change your onclick events as follows:
Change onlick functions to this: onclick ="myFunction(this)"
And Update your javascript function to be like the following:
function myFunction(obj) {
if (obj.value == "Connected")
obj.value = "Connect";
else
obj.value = "Connected";
}
You cant use same Id for multiple elements. Simply you can use class instead of Id. Then your code will look like that :
$(".toggle").click(function(){}
$(this).text("Whatever");
})

How to change a string within a div that your selector is in with JQuery?

How do you change the name of text within a div that your selector is inside of? In other words, I'd like to click on a button and change the text of the text above the button (within the same div).
For example, in my html, there is a button and a title above it. Once the button is clicked, I'd like the title above it to change to the id of the button.
This problem is similar to this question, but I'm having difficulty changing the text within the div that the selector is in.
Below is my attempt to grab the id of the button, and change the text within the div container.
Javascript (my attempt) (codepen here):
$('.btn.btn-default').on('click', function() {
var desired_name = $(this).attr('id')
$('#title').find($(this)).html(desired_name);
});
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p id="title">Temporary Button Title That Should be 'true_name1'</p>
<button class="btn btn-default" id="true_name1">NAME</button>
</div>
<div>
<p id="title">Temporary Button Title That Should be 'true_name1'</p>
<button class="btn btn-default" id="true_name2">NAME</button>
</div>
Have you tried $(this).siblings("p")
This will select the <p> above the button
Have you tried jquery .prev()
https://api.jquery.com/prev/
$('.btn.btn-default').on('click', function() {
var desired_name = $(this).attr('id')
$(this).prev().html(desired_name);
});
You can use the jQuery method siblings() to select the <p> element inside your <div> container.
However I recommend using a class as a unique selector inside your container.
$('.btn.btn-default').on('click', function() {
$(this).siblings(".desired-name").text($(this).attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p class="desired-name">Temporary Button Title That Should be 'true_name1'</p>
<button class="btn btn-default" id="true_name1">NAME</button>
</div>
<div>
<p class="desired-name">Temporary Button Title That Should be 'true_name1'</p>
<button class="btn btn-default" id="true_name2">NAME</button>
</div>
Change the ID's to classes for starters. Then target them like this:
$('.btn.btn-default').on('click', function() {
var desired_name = $(this).attr('id');
$(this).prev(".title").text(desired_name);
});

adding div around link using jquery

I am adding a div around a link on click of a button. but when i click button multiple times, it adds multiple divs.
<li>
<label> </label>
<div class="deletebutton">
<label> </label>
<div class="deletebutton">
<label> </label>
<div class="deletebutton">
<input type="button" id="ctl00_ContentPlaceHolder1_ctrlAddPhotos_RadUpload1remove1" value="Remove" class="ruButton ruRemove" name="RemoveRow">
</div>
</div>
</li>
How can i make sure that it first checks if there is a div around link and then adds.
I am using following code:
var parentTag = $(".ruRemove").parent().get(0).tagName;
if (parentTag == 'LI') {
$(".ruRemove").wrap("<div class='data deletebutton'></div>");
$(".deletebutton").before("<label></label>");
} else {
var par = $('.deletebutton').parent();
if (par.is('div')) par.remove();
$(".ruRemove").wrap("<div class='data deletebutton'></div>");
var prev = $('.deletebutton').prev();
if (prev.is('label')) prev.remove();
$('.deletebutton').before("<label></label>");
}
it should become this:
<li>
<label> </label>
<div class="deletebutton">
<input type="button" id="ctl00_ContentPlaceHolder1_ctrlAddPhotos_RadUpload1remove1" value="Remove" class="ruButton ruRemove" name="RemoveRow">
</div>
</li>
when i click button. before clicking html is:
<li>
<input type="button" id="ctl00_ContentPlaceHolder1_ctrlAddPhotos_RadUpload1remove1" value="Remove" class="ruButton ruRemove" name="RemoveRow">
</li>
Here is a solution shown in a jsFiddle.
The code story is
HTML
<button id="myButton">My Button</button
JavaScript
$(function() {
$("#myButton").click(function() {
if ($(this).parent().get(0).tagName !== "DIV") {
$(this).wrap("<div class='myDiv'>");
}
});
});
What the code does is register a callback for a button click. When clicked, we ask for the parent of the button that was clicked and ask if the parent node has a tag name of "DIV" meaning it is a <div>. If it is not a div, then we wrap the button in a div and end. On the next call, the detection of the parent being a div will be true and no new div will be added.
Why don't you just use for example a function that does what you want only on the first click?
So only on the first click of that button adds the div, if you click other times the button, it wont do anything. This way you wont add multiple divs.
To do that you could use for example jQuery:
<script type="text/javascript">
$("#firstclick").one("click",function() {
alert("This will be displayed only once.");
});
</script>
You can check even the jQuery API Documentation regarding one:
http://api.jquery.com/one/

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