How can I update a text based on user input? - javascript

I know this is probably simple, but how do you update a text based on a user's input?
For example, I have an email template that starts out like this:
*Greetings,
My name is __ and I'm the author of ___ which is available on Amazon.com.*
I would like to create some simple input fields for the user to insert their name and the title of their book. There are several more inputs as well. I would just need the final output to give them the full text of the template with their own info inserted in the right places, based on what they submit.
What is the easiest and simplest way to accomplish this? Thank you in advance.

If you don't find an easer way you can use jQuery:
$(document).ready(function() {
$('.my-inputs').each(function() {
$(this).on('keyup', function() {
var name = $('#name').val() == '' ? '___' : $('#name').val();
var book = $('#book').val() == '' ? '___' : $('#book').val();
$('#result').html("*Greetings, My name is " + name + " and I'm the author of " + book + " which is available on Amazon.com.*");
});
});
});
http://jsfiddle.net/XEzBw/

Use this.
$('button').click(function () {
var str = 'Greetings, My name is ' + $('#name').val() + 'and I\'m the author of ' + $('#book').val() + ' which is available on Amazon.com.';
$('#template').html(str);
});
Demo: http://jsfiddle.net/7bLJK/

Seems that you are you searching for a simple format method, and for this you have to use any plugin.
Otherwise:
<input type="text" id="inputName"></input>
<input type="text" id="inputAuthor"></input>
var name = $('#inputName').val();
var author = $('#inputAuthor').val();
var t = "*Greetings, My name is " + name + " I'm the author of " + author + " which is available on Amazon.com.";
You can try DEMO here.

Related

Why jQuery append() removes words after first blank space in string

I'm trying to dynamically generate a form after an ajax request. Below is the relevant code sample :
for (var i in response.responseJSON[0].fields) {
var field = response.responseJSON[0].fields[i];
$('#properties_form').append('<label for=' + i + '>' + i + '</label>' +
'<input id=' + i + ' value=' + field + '>');
}
My problem is that, when var i and var field are strings with blank spaces like "Hello world", my label and inputs will be like <label id="Hello" world=""> and <input value="Hello" world="">. However, the label text will be displayed correctly i.e. <label>Hello world</label>.
I've no idea what kind of sorcery that is, but I'll be very grateful for any help. Thanks in advance.
There's a much more robust way of doing this.
for (var i in response.responseJSON[0].fields) {
var field = response.responseJSON[0].fields[i];
$('#properties_form')
.append($('<label>').attr('for', i).text(i))
.append($('<input>').attr('id', i).val(field));
}
You won't have to worry about the content of the strings as jQuery and the DOM will handle it for you. Not to mention this is much easier to read.
Use " to enclose the attributes.
$('#properties_form')
.append('<label for="' + i + '">' + i + '</label>' +
'<input id="' + i + '" value="' + field + '">');
EDIT
This will break for the cases where the value for i is something like This "works". Best solution is to append as jQuery or JS objects rather than using HTML string just like Daniel's answer.
Following snippet contains the correct fix for this. Updated based on the answer from Daniel.
i = 'Hello "World"';
field = 'Hello "World"s';
$('#properties_form')
.append($('<label>').attr('for', i).text(i))
.append($('<input>').attr('id', i).val(field));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="properties_form"></div>

attempting to split string dynamically keep getting error?

I'm attempting to split a string I'm passing into
$("#groupUL").append("<li>" + "<h2>About Item:</h2> " + response.data[i].message + "<br /> " + "<h2>Posted By:</h2> <a href='#' onclick='splitName('" + response.data[i].from.name + "');'>" + response.data[i].from.name + "</a>" + "<br />");
Seems to be passing me the error
SyntaxError: syntax error
splitName(
Not sure how that's wrong...Here is the splitname function if that helps
function splitName(txt){
var myString = txt;
var mySplitResult = myString.split(" ");
console.log("The first element is " + mySplitResult[0]);
console.log("<br /> The second element is " + mySplitResult[1]);
console.log("<br /> The third element is " + mySplitResult[2]);
};
It's too hard to get it right when you put quotes in quotes in quotes and you try to escape it right. You got it wrong.
A solution is to make it in small parts :
var action = "splitName('" + response.data[i].from.name + "');";
$("#groupUL").append("<li>" + "<h2>About ... onclick=\""+action+"\">...");
But the best solution would be to follow best practice, that is not inline the javascript but use jQuery's binding function :
$("#groupUL").append("... <a id=myid ...");
$("#myid").click(function(){ splitName(response.data[i].from.name) });
I think the only problem with your code is with your readability issue. So I would suggest please improve it. Lets have a look at it. My code example # JSbin.
Here is the code :- (which i think is better)
var response = {
data : {
message: 'Cleaning code',
from: {
name: 'Clean Code works'
}
}
};
var li = $('<li>'); //Create empty li (Not Appending to DOM now due to performance issues)
$('<h2>').html('About Item:' + response.data.message + '<br />').appendTo(li);
$('<h2>').html('Posted By:').appendTo(li);
$('<a>').attr('href', '#')
.html(response.data.from.name)
.appendTo(li)
.click(function() {
splitName(response.data.from.name);
});
$('<br>').appendTo(li);
// Append li to ul (Final operation to DOM)
li.appendTo('#groupUL');
function splitName(txt){
var myString = txt;
var mySplitResult = myString.split(" ");
console.log("The first element is " + mySplitResult[0]);
console.log("The second element is " + mySplitResult[1]);
console.log("The third element is " + mySplitResult[2]);
}

.val() not getting updated value from input

I have two input fields, and I'm trying to get their values using jquery by clicking a button. It seems like a very simple operation, but for the life of me I can't get it to work. Here is the code snippet:
Name: <input type="text" id="name" value="test1"><br>
Message: <input type="text" id="line" value="test2"><br>
<button id="submitButton">Submit</button>
<script>
name1 = $("#name").val();
line1 = $("#line").val();
$("#submitButton").click(function(){
alert("Name: " + name1 + "\nMessage: " + line1);
});
</script>
If I don't specify the value, the alert returns with undefined for both variables. If I change the values of the input and click the button, it still says test1 and test2. There has to be something simple that I'm missing here, anyone know what it is?
In your code, you fetch the values when the script is initialized, and then reference the value they had at that point in your click function rather than fetching the current value.
Try:
$("#submitButton").click(function(){
name1 = $("#name").val();
line1 = $("#line").val();
alert("Name: " + name1 + "\nMessage: " + line1);
});
name1 = $("#name").val()
creates a new string variable name1 that has the value of $("#name").val() as it is at the moment. .val() does not get called each time you try to access name1. The simplest thing to do would just be to use $("#name").val() instead.
http://jsfiddle.net/wTvku/
As mentioned in other answers, the problem is that you are precomuting the variables and expecting them to magically change. However I would strongly suggest using Vanilla JS
document.getElementById('submitButton').onclick = function() {
var name1 = document.getElementById('name').value,
line1 = document.getElementById('line').value;
alert("Name: " + name1 + "\nMessage: " + line1);
};
you should wrap your code within document.ready() event...
$(document).ready(function() {
name1 = $("#name").val();
line1 = $("#line").val();
$("#submitButton").click(function(){
alert("Name: " + name1 + "\nMessage: " + line1);
});
// Handler for .ready() called.
});
You've set variable values outside of the click function. To the value is set on page load, not whenever you run the function. Try this:
Name: <input type="text" id="name" value="test1"><br>
Message:
Submit
$("#submitButton").click(function(){
name1 = $("#name").val();
line1 = $("#line").val();
alert("Name: " + name1 + "\nMessage: " + line1);
});

Adding .val() without variable

I'm trying to get the value of an input, but I can't have this:
$('#inputID').val();
Inside a seperate variable.
I have the following code:
var click = "$('#highlight"+n+"').replaceWith('<span id="+id+ " style="+c+">" + $("#input" + n + "").val() + "</span>');$('#black"+n+"').hide();$('#replace_box"+n+"').remove();";
This variable is not receiving the value of the input.
Can you explain to me why the following will not work?
$('#highlight"+n+"').replaceWith('<span id="+id+ " style="+c+">" + $("#input" + n + `"").val() + "</span>');`
And can I please get a solution. Cheers.
I try some mind reading but this code won't work because you have wrong quotes:
$("#highlight"+n).replaceWith("<span id="+id+" style="+c+">"+$("#input" + n).val() +"</span>");
in any case this code would be better:
var span = $('<span />', {id: id, style: c});
span.html($("#input" + n).val());
$("#highlight"+n).replaceWith(span);

popualte textbox from values on screen with javascript

how can I use the values from the code below:
<html:select property="state" >
<html:option value="0">Select State</html:option>
<html:optionsCollection name="InputForm" property="stateList" label="label" value="value" />
</html:select>
to populate a textbox with whatever the selected value is for the state with a javascript onchange event? for example if texas is the selected state I want Texas to be written in the textbox and if I change the value to Colorado I would like Colorado and Texas to both show in the textbox. I am currently getting an undefined value in the textbox. I am using the following javascript code:
function displayState(obj, state) {
var theId = obj.id.substring(obj.id.indexOf('_') + 1);
var text = document.getElementById('text' + '_' + theId);
var textVal = text.value;
var stateSelect = document.getElementById('stateCode' + '_' + theId);
var stateSelectStr = new String(stateSelect.value);
var stateSelectSplit = stateSelectStr.split(',');
var stateSelectValue = stateSelectSplit[0];
var stateSelectLabel = stateSelectSplit[1];
if (stateSelectValue == '51') {
stateSelectLabel = '';
}
if (stateSelectValue != '00') {
textVal = textVal != '' ? eval('text.value=\'' + textVal + ', '
+ stateSelectLabel + '\'')
: eval('text.value=\'' + stateSelectLabel + '\'');
}
}
First off, start using jQuery (or equivalent), it will make your life much easier. Second, why are you using eval? You already have the text element; just build the appropriate string and set the value. See here for an example.
But again, using something like jQuery makes this laughably easy--I can't recommend using a library for simple DOM manipulation like this.
See here for a comparison between raw JS and JQ.

Categories

Resources