Edit text of button onclick - javascript

What I would like to do is have the text of a button that is editable upon clicking.
I understand how to change the value to one that is hard-coded but what I would like is...
Click the button and a field will appear.
This field would allow you to type in a new name for the button.
After submitting the field, the text of the button would have changed to the field value.
The goal is a button that has a text value which is editable and other buttons which increment a number value associated with how many of the field there are.
| - | Item Name - 1 | + |
or
[subtraction button] | Name of Item - # of item | [addition button]
Thank you very much for your help and time.

See this fiddle
What I have done is that I'll get the text entered in the input field and use it to set the Text of the Button in onClick event of the button.
HTML
<input type="text" id="btn_text" />
<button onclick="myFunction()" id="btn">Click me</button>
JS
function myFunction() {
document.getElementById("btn").innerHTML = document.getElementById("btn_text").value;
}

Did you write your code? You can post it, but if not, you can do the following:
jQuery
$("button").click(function(e) {
e.preventDefault();
$("input").show();
});
$("input").blur(function() {
$("button").text($(this).val());
$(this).val("");
$(this).hide();
});
Or want you a pure js
var bt = document.getElementsByTagName("button")[0];
var input = document.getElementsByTagName("input")[0];
bt.addEventListener("click", function() {
input.style.display = "inline";
});
input.addEventListener("blur", function() {
bt.innerText = this.value;
this.style.display = "none";
this.value = "";
});
html
<button>Click me</button>
<input type="text" style="display:none">
Demo using jQuery: http://jsfiddle.net/x8714jgk/
Demo using pure Js: http://jsfiddle.net/x8714jgk/1/

Related

How can I automatically file an input box and click a search button?

I tried to fill a search input field with some text and hit the search button with this code:
document.getElementsByName('search')[0].value = '1234978';
document.getElementsByClassName('js_search_button')[0].click();
I see my text in the box and the button gets hit. But the data from the input box, was not submited.
Maybe the website has a protection, so that only keytrokes are accepted.
To crosscheck this I tried this code:
var iButton = document.getElementsByClassName('js_search_button')[0];
iButton.addEventListener('click', simulateInput);
function simulateInput() {
var inp = document.getElementsByName("search")[0];
var ev = new Event('input');
inp.value =inp.value + '1234978';
inp.dispatchEvent(ev);
}
Here I get the right result if I manualy click the searchbutton with automaticly filled in the number.
I it possible to automate the click in this scenario, too ?
This is not an answer, because of code sample I posted it as answer.
Are you selecting the right element for clicking? As you can see I click the buttons programmatically.
function clicked(val) {
console.log('button clicked:', val)
}
document.querySelectorAll(".txt")[0].value = 5;
document.querySelectorAll('.btn')[1].click()
document.querySelectorAll('.btn')[2].click()
document.querySelectorAll('.btn')[0].click()
document.getElementsByClassName('btn')[3].click()
<input class='txt' type='text' />
<button class="btn" onclick="clicked(1)">a</button>
<button class="btn" onclick="clicked(2)">b</button>
<button class="btn" onclick="clicked(3)">c</button>
<button class="btn" onclick="clicked(4)">d</button>

Edit/Cancel Button in Javascript

I have a form where the user can edit their text. I want the user to be able to retrieve their text if they delete it by hitting the cancel button.
How would I be able to retrieve a users text if they edit the original text, and when they press cancel the original text in the form before the edit comes back?
You could use data-* attributes to do this by adding data-original-text to the input like :
<input name='first_input' data-original-text='First input text' value="First input text"/>
And add a click event to the cancel button that will get the data attribute and assign it to the value :
$('form').on('click','#cancel',function(){
$(this).closest('form').find('input').each(function(){
$(this).val($(this).data('original-text'));
})
})
Hope this helps.
$('form').on('click','#cancel',function(){
$(this).closest('form').find('input').each(function(){
$(this).val($(this).data('original-text'));
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input name='first_input' data-original-text='First input original text' value="First input original text"/>
<input name='second_input' data-original-text='Second input original text' value="Second input original text"/>
<button id='cancel'>Cancel</button>
</form>
Something like the following could be built upon so that they could make multiple changes and still have the previous text available on change.
// JavaScript source code
var orginalText = "Please Enter Some Text here";
var newTest = "";
$(document).ready(function () {
$("#target").change(function () {
newText = this.text;
});
$(".cancel").on("click", function () {
$("#target").text(orginalText);
});
});

How to POST additional values from inputs outside the form [duplicate]

I've read many blogs and posts on dynamically adding fieldsets, but they all give a very complicated answer. What I require is not that complicated.
My HTML Code:
<input type="text" name="member" value="">Number of members: (max. 10)<br />
Fill Details
So, a user will enter an integer value (I'm checking the validation using javascript) in the input field. And on clicking the Fill Details link, corresponding number of input fields will appear for him to enter. I want to achieve this using javascript.
I'm not a pro in javascript. I was thinking how can I retrieve the integer filled in by the user in input field through the link and displaying corresponding number of input fields.
You could use an onclick event handler in order to get the input value for the text field. Make sure you give the field an unique id attribute so you can refer to it safely through document.getElementById():
If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">. Create new elements by means of document.createElement(), and use appendChild() to append each of them to the container. You might be interested in outputting a meaningful name attribute (e.g. name="member"+i for each of the dynamically generated <input>s if they are to be submitted in a form.
Notice you could also create <br/> elements with document.createElement('br'). If you want to just output some text, you can use document.createTextNode() instead.
Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes() and removeChild() together.
<html>
<head>
<script type='text/javascript'>
function addFields(){
// Generate a dynamic number of inputs
var number = document.getElementById("member").value;
// Get the element where the inputs will be added to
var container = document.getElementById("container");
// Remove every children it had before
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
// Append a node with a random text
container.appendChild(document.createTextNode("Member " + (i+1)));
// Create an <input> element, set its type and name attributes
var input = document.createElement("input");
input.type = "text";
input.name = "member" + i;
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement("br"));
}
}
</script>
</head>
<body>
<input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
Fill Details
<div id="container"/>
</body>
</html>
See a working sample in this JSFiddle.
Try this JQuery code to dynamically include form, field, and delete/remove behavior:
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e) {
e.preventDefault();
if (x < max_fields) {
x++;
$(wrapper).append('<div><input type="text" name="mytext[]"/>Delete</div>'); //add input box
} else {
alert('You Reached the limits')
}
});
$(wrapper).on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container1">
<button class="add_form_field">Add New Field
<span style="font-size:16px; font-weight:bold;">+ </span>
</button>
<div><input type="text" name="mytext[]"></div>
</div>

Linking form and button to javascript command

I am trying to make a simple form and button work. I have linked to a JS Fiddle here View JS Fiddle here
<form>
<input type="text" class="form-control" id="search" placeholder="enter sport">
<button type="submit" id="WFFsearch">Search</button>
</form>
$('#WFFsearch').on('click', function () {
var searchInput = $('#search').text();
var url = "http://espn.go.com/" + searchInput + "/statistics";
window.open(url);
});
I want to be able to enter "nba" without the quotation marks and click the search button, then have a new window which generates the following link http://espn.go.com/nba/statistics. The first part and the last part of all the urls will be the same, it's just the middle that changes (nba, nfl, mlb). Any help would be greatly appreciated, thanks!
$('#WFFsearch').on('click', function () {
var searchInput = $('#search').val();
var url = "http://espn.go.com/" + searchInput + "/statistics";
window.open(url);
});
You need val() property, since input is in question, not text(). https://jsfiddle.net/1c93pqj0/2/
you wanna use the .val() instead of .text() as text gets the value between 2 tags <div>here is some text</div> and val gets the value <input value="some value"/>
EzPz! This is a very simple task. First of all though, since you're using jQ to establish your button's click event, you can either drop the attribute type="submit", OR (recommended), create your event on the form's submit. If it were me, I'd id the form and use the forms submit, so that you don't need any alters to your button type="submit" and enter key can still be used in search box to submit the form.
Also, you're trying to .text on an input. Input's have value. In jQuery you can get or set that value by calling .val() instead.
The code:
$('#frmGetStats').on('submit', function (e) {
e.preventDefault();
var searchInput = $('#search').val(),
url = "http://espn.go.com/" + searchInput + "/statistics",
win = window.open(url);
alert("In this sandbox, new windows don't work. \nHowever you can see the link is \n[" + url + "]");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="frmGetStats">
<input type="text" class="form-control" id="search" placeholder="enter sport">
<button id="WFFsearch" type="submit">Search</button>
</form>
To get the value of an input field, use .val(). .text() is for the text in a DOM element.
Clicking on the submit button submits the form by default, which reloads the page and kills the script. You need to return false from the event handler to prevent this.
$('#WFFsearch').on('click', function () {
var searchInput = $('#search').val();
var url = "http://espn.go.com/" + searchInput + "/statistics";
window.open(url);
return false;
});
DEMO

Taking a HTML form <input> value and using it to modify a <p> tag with Javascript

I am fairly new to Javascript and am trying to create a simple madlib application where a user can input a word through an HTML page and have that word appear in a paragraph tag when the user clicks the "submit" button. I am having troubles displaying the word that the user inputs. I know that I am close but for the life of me cannot figure out what I am missing.
Here is the HTML I am using:
<form>
<label>Word</label><input id="word"></input>
<input type="submit" value="submit" id="submitButton"></input>
</form>
<p id="story"> A {userWord goes here} is now part of the story </p>
And the Javascript:
var word = document.getElementById('word').innerHTML,
originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(){
replaceStory(word);
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
return originalStory.innerHTML = story;
};
Here is a JSFiddle: https://jsfiddle.net/5c4j2opc/
I have made a new JSFiddle: https://jsfiddle.net/5c4j2opc/3/ which works.
I changed type="submit" to type="button" to stop the page refreshing when the button is clicked and moved the word variable to the replaceStory function so it doesn't just get called once at the beginning of the script! Hope this helps.
You have to change two things.
The first is you are using innerHTML in a input element, when you want to access input element you need to get the value not the innerHTML, inputs not have this property.
The second one is that you need to pass the event on the onclick event since if you don't do it you can't cancel the submit action and then the page will be submit it automatically and reload the content. Then after you pass the event you have to apply event.preventDefault which will stop the submit for that button. Other option to avoid this problem would be possible to replace the submit button with a <button> tag or <input type="button"> since not of them will trigger the submit action.
You can see a working example https://jsfiddle.net/5c4j2opc/9/
html -> same you have
javascript
var word = document.getElementById('word'),
originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(e){
replaceStory(word.value);
e.preventDefault();
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
return originalStory.innerHTML = story;
};
You initialize wordjust in the beginning of the script. Besides, that the input value is not innerHTML, during that time, the value is empty.
As long as the return value is not set explicitly to false, the form will reload the page and overwrite any result.
Change your code:
var originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(){
var word = document.getElementById('word').value;
replaceStory(word);
return false;
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
originalStory.innerHTML = story;
};
updated fiddle
You had a couple of minor problems. The input type of the submit button should be button rather than submit. Submit does a post request and refreshes the page with the data received.
Initially you had:
var word = document.getElementById('word').innerHTML this would get the initial innerHTML which would be nothing. You have to get the inner text within word every single time the button is clicked to get the most recent text inside the textbox.
Finally, for a input node you should get .value rather than .innerHTML to get the inner text
html:
<form>
<label>Word</label><input id="word"></input>
<input type="button" value="submit" id="submitButton"></input>
</form>
<p id="story"> A {userWord goes here} is now part of the story </p>
javascript:
var word = document.getElementById('word'),
originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(){
replaceStory(word.value);
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
return originalStory.innerHTML = story;
};
I advise you to just understand Javascript first, and after then, focus on learning Jquery because it's much more easier and handy.
By the way if you want to do what you said:
You shouldn't use form tag, because you don't want to send something to server-side and you can use div tag as well instead of form tag.
<div>
<label>Word</label>
<input id="word" type="text"></input>
<button id="submitButton">Submit</button>
</div>
<span>A </span><span id="text">{here}</span><span> is now part of the story</span>
Jquery
$('#submitButton').click(function(){
txt = $('#word').val()
$('#text').text(txt);
});
Don't forget to import Jquery Package.
https://jsfiddle.net/softiran/gt8rr5pe/
You could also allow the user to change your story directly. I know this may not use an input tag, but it was very useful to me.
<div id="story">Once upon a time there was a man named
<p id="added" contenteditable="true" title="Click to change">
Bill</p>. He liked to eat tacos.</div>
I used this in a code that changed the name of the main character of a story into a user-selected name and allowed them to download the story. Hope this helps! All the user has to do is click the name "Bill" and they will be able to change the name to anything they want.

Categories

Resources