div text to input value - javascript

Scenario :
After double quote,next characters were not displaying.
I know this is because of escaping of single and double quotes, I have tried this regex (/"/g,'\"'), but its not working.
Can someone help me review the code?My wanted output is that all characters on div should also display on input.
PS: I want to avoid replace(/"/g,'"') as much as possible.
<div>single ' double " single ' </div>
<form>
</form>
$("form").append('<input type="text" value = "' + $("div").text().replace(/"/g,'\"') + '" />');
see this Fiddle demo

Try this method (demo):
$('<input>', {
type: 'text',
value : $("div").text()
}).appendTo('form');
Update: for multiple elements, try this (demo)
var txt = $('div').text();
$('<tr><td><input type="button"></td><td><input type="text"></td></tr>')
.appendTo('table')
.find('input')
.val( txt );

Related

Can't insert line break in Ajax outputString

I have an Ajax script that outputs both the title and description of certain jobs based on user input. While I can get these displaying without issue, I can't seem to insert a line break between the title and description. I have the following:
outputString = savedData[i].firstName + ". Description: " + savedData[i].cardNumber;
var paragraph = $("<p />", {
text: outputString
});
$("#data").append(paragraph);
I have tried inserting a traditional br line break, as well as, \n and \r\n both in the quotation marks before description which just displays the text of the line break rather than breaking the line, and also outside of the quotation marks which breaks any output. How can I successfully implement a linebreak?
Cheers.
As you are providing the outputString string as text, the html <br/> is being displayed as text in the string. You should specify it in as html and use <br/> for line break:
outputString = dataJobs[i].title + ". <br/>Description: " + dataJobs[i].description;
var paragraph = $("<p />", {
html: outputString
});
$("#data").append(paragraph);
If you would like to add a <br/> specifically, then you can do the following:
// assuming that your dataJobs[i].title and dataJobs[i].description are defined
var paragraph = $("<p />");
paragraph
.append(dataJobs[i].title + '.')
.append('<br />')
.append("Description: " + dataJobs[i].description);
$("#data").append(paragraph);
You need to add a <br/> in a separate append call, but not as part of a string. Hope this helps.
In the code below as the P tag has display property set to block by default, so there is no need for using line break.
Setting Title and Description in two different P tags that will solve your problem
Try the following code.
outputString = "<p>Title: "+dataJobs[i].title+"</p><p>description: "+dataJobs[i].description+"</p>";
$("#data").append(outputString);
I think the "jQuery way" should look like this:
var $outputString = $( "<span>" + dataJobs[i].title + ".<br>Description: " + dataJobs[i].description + "</span>" );
$( "#data" ).append($outputString.wrap( "<p></p>" ));
outputString = dataJobs[i].title + ". Description: " + dataJobs[i].description + "<br/>";

Variable in the middle of a string

$('#attachments').append("<tr><td><b>Attachment " + next + "</b><input id='upload" + next + "'name='files'" + "onchange='showUpload('" + next + "') type='file' value='System.Collections.Generic.List`1[System.Web.HttpPostedFileBase]'></td></tr>");
The above code is printing the following in the browser. What am I doing wrong?
<input id="upload1" name="files" onchange="showUpload(" 1') type="file" value="System.Collections.Generic.List`1[System.Web.HttpPostedFileBase]" class="valid" aria-invalid="false">
onchange="showUpload(" 1') needs to be onchange="showUpload('1')
I recommend using string interpolation (template literals) instead. To find out if your browser supports template literals, check Can I Use.
It's far easier to get this right. I've added newlines so it's readable. Making your HTML on one line like that is just impossible to read:
var content = `<tr><td>
<b>Attachment ${next}</b>
<input id="upload${next}"
name="files"
onchange="showUpload('${next}')"
type="file"
value="snipped for brevity">
</td></tr>`;
$('#attachments').append(content);
What this does is fairly intuitive: the template literal, delineated by backticks, will replace each instance of ${next} with the value in the next variable.
I have also taken the liberty to change all of your attributes to use double quotes for consistency. Hopefully I didn't make any typos.
Superficially "onchange='showUpload('" closes the onchange value before the function's parameter, which leads to malformed HTML.
What am I doing wrong?
What you're really doing wrong is that you're adding inline event handlers with jQuery, which leads to problems exactly like that.
var tr = $("<tr><td><b>Attachment " + next + "</b></td></tr>").appendTo("#attachments");
$('<input>', {
id: "upload" + next,
name: "files",
type: "file",
value: "System.Collections.Generic.List`1[System.Web.HttpPostedFileBase]"
}).on( 'change', function() { showUpload(next); } )
.appendTo(tr.find('td'));
You can simply escape a character
$('#attachments')
.append("<tr><td><b>Attachment " + next + "</b><input id='upload" + next + "' name='files' onchange='showUpload(\"" + next + "\")' type='file' value='System.Collections.Generic.List`1[System.Web.HttpPostedFileBase]'></td></tr>");

Having difficulty building a form summary with JS

Sorry for the noobish question but, I am trying to build a form summary that will populate a div (immediately) with all of the fields being used. Here is a small sample of the field: Fiddle
For some reason the JS is not working as I would expect it to, can anyone point out what I am doing wrong?
For example, I would like it to output: "AND name: john EXCEPT number 222".
I would also like to be able click on a result to remove it, and clear the field. Thank you
$(".allS").change(function () {
if ($(this).next('.textArea').not(':empty'))
// varible to hold string
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("#text_here").text(str);
}).change();
$('.textArea').change(function(){
var $inputs = $('form#form :input[type="text"]'),
result = "";
$inputs.each(function(){
// access the individual input as jQuery object via $(this)
result += $(this).val()+"<br>";
});
// store result in some div
$('div#text_here').text(result);
}).change();
There were many mistakes in your code. I simplified it to a very short code that only does what's needed to get the output you requested. Here's the working fiddle.
$(".allS, .textArea").change(function () {
var str = '';
if ($('#name').val().length > 0 && $('#number').val().length > 0)
var str = $('#nameMod>option:selected').text() + ' name:' + $('#name').val() + ' ' + $('#numberMod>option:selected').text() + ' number ' + $('#number').val();
$("#text_here").html(str);
});
Basically, what this does is attach a change event handler to both classes (.alls, .textArea), and when the event is triggered, both input fields are tested for any content. If this test passes, a string is composed out of all the relevant values, and the div content is set. If the test failed (no content), the str variable contains an empty string and the div is cleared.
Just glancing at the code, the selector 'form#form :input[type="text"]' looks wrong. For starters, input is not a pseudoclass. Also, attribute matching shouldn't have the quotes.
This may or may not be what you want (I think it is, from looking at your html):
'form#form input[type=text]'
Also your <br>'s are not working because you called text(). call html() instead.

Taking literals out of phone number using .val()

I am trying to remove the literals in a phone number (999) 999-9999 to make it 9999999999 in another hidden input value.
Can this be accomplished using the .val() function or can you only add more values to the hidden input?
phone1= (999) 999-9999
phone should have this value= 9999999999
$('#phone1').bind('keypress blur', function() {
$('#phone').val($('#phone1').val() + ' ' );
});
get value
run string replace
set value
Basic idea with a plain string
var str = "(999) 999-9999 ";
var newStr = str.replace(/\D/g,"");
console.log(newStr);
Now the best way to write what you did would be
$('#phone1').on('blur', function() { //jQuery 1.7.2+ use on, not bind
var txtBox = $(this);
txtBox.val( txtBox.val().replace(/\D/g,"") );
});
You need the replace [MDN] method. It's what's going to do most of the work for you:
$('#phone').val($('#phone1').val().replace(/\D/g, ''));
The first parameter can be either a substring or a regular expression. In the example, I've used the regex for "not a digit".
$('#phone1').on('keypress blur', function() {
$('#phone').val(this.value.replace(/[^\d]/g, "") + ' ' );
});
FIDDLE

javascript Firebug error: Identifier starts immediately after numeric literal

I've got this error being reported in firebug, but I have no idea what it means:
Identifier starts immediately after numeric literal
Here is my webpage:
http://www.austintreeexperts.com/maps/optionUpdateMap.cfm?zoom=15
When the page and map loads, click on one of the blue or green markers. Then click on one of the check boxes to get the error. I have an onclick= for the input checkboxes.
Your string concatenation is broken. You need to wrap your method parameters in quotes
var statusForm = '<input id="tU'+Aid+'" type="checkbox" onclick="optionAUpdate(tU'+Aid+', '+color+', '+optionB+')"/> option A | <input id="iU'+Aid+'" onclick="optionBUpdate(iU'+Aid+', '+color+', '+optionA+')" type="checkbox"/> options B';
From here ----------------------------------------------------------------------------^
Corrected version
var statusForm = '<input id="tU' + Aid + '" type="checkbox" onclick="optionAUpdate(\'tU' + Aid + '\', \'' + color + '\', \'' + optionB + '\')"/> option A'
Note : I've treated all your params as strings
Your onclick needs to be:
optionAUpdate('tU20238', '75AB5F', 0)
Note that I wrapped the params in quotes as they are strings.
This message also appears if you've tried to name a variable starting with a numeral. eg.
var 2ndString = 'abc';
<input
id="is-ib-checkbox"
value='+accWidgetData[count]["userAccountNumber"]+'
onchange="addaUserAccount(\'' + accWidgetData[count]["userAccountNumber"] + '\' );"
value="true"
checked="checked"
type="checkbox"
/>
For this case, in my code:
html.input()
.onclick("selectItem(" +"'"+cons.getIdentificacion().toString()+"'" + ");")
.type("radio")
.name("selectedItem")
.style("vertical-align: text-bottom")
.close();
works Fine.

Categories

Resources