on loading html through javascript, textbox value doesn't consider space - javascript

Below given is a fraction of code, which loads a table row dynamically through html. The table row has a textbox, which gets its value from the variable 'currentValue'. But if the content of 'currentValue' has a space in between, only the first word is displayed. Nothing after space is displayed in the textbox(In below code, only 'hello' is displayed). Please suggest some solutions other than setting value through separate javascript query.
currentValue = 'hello world';
tr.append("<td><input id="+ textBoxId1 + " class='MyTextBox1' type='text' name='parameter_label' value="+ currentValue +" maxlength="+stringMaxLength+"></input></td>");

Think about the HTML you're producing. Suppose currentValue has "something here":
<td><input id=someid class='MyTextBox1' type='text' name='parameter_label' value=something here maxlength=40</input></td>
<!-- Notice ---------------------------------------------------------------------^^^^^^^^^^^^^^ -->
Now it should be obvious what the problem is (and that there are two other problems): You don't have quotes around the value attribute's value. That's only valid when the value doesn't have spaces (or several other characters). More in the specification.
So we add them:
tr.append("<td><input id="+ textBoxId1 + " class='MyTextBox1' type='text' name='parameter_label' value='"+ currentValue +"' maxlength="+stringMaxLength+"</input></td>");
// Note -----------------------------------------------------------------------------------------------^------------------^
That assumes that currentValue will never have ' in it. If it might, you can use " instead:
tr.append("<td><input id="+ textBoxId1 + " class='MyTextBox1' type='text' name='parameter_label' value=\""+ currentValue +"\" maxlength="+stringMaxLength+"</input></td>");
// Note -----------------------------------------------------------------------------------------------^^------------------^^
That assumes currentValue will never have " in it, or that you've properly prepped currentValue (handling turning < and & into entities, as you must for all attributes, and also in this case turning " into ").
The other two problems are:
You're missing the ending > on your <input ...> element.
Remove the </input>. input elements are void elements, they never have closing tags.
So:
tr.append("<td><input id="+ textBoxId1 + " class='MyTextBox1' type='text' name='parameter_label' value='"+ currentValue +"' maxlength="+stringMaxLength+"></td>");

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/>";

Change checkbox and label for ID

I have a function that is replacing placeholders in a string of HTML with content from JS objects:
function inputCards() {
$('#maincontent').empty();
storyQuests.name.forEach(function(val, i) {
var formattedCard = mainCardHTML.replace('%questName%', storyQuests.name[i])
.replace('%questChapter%', storyQuests.chapter[i])
.replace('%questImg%', storyQuests.img[i])
.replace('%questDescription%', storyQuests.description[i])
.replace('replaceBox', storyQuests.check[i]);
$('#maincontent:last').append(formattedCard);
})
}
This is how the code is now, the problem I ran into is that I am using materialize and the checkbox code on a card is:
<div class="card-action">
<form action="#">
<p>
<input type="checkbox" id="replaceBox" />
<label for="replaceBox" class="white-text">Complete!</label>
</p>
</form>
</div>
Everything on the page is going OK, except when it loads all the cards ALL of the checkboxes when clicked only effect the checkbox in the first card! So I assumed this was because they all had the same ID of "replaceBox". So I added this to solve it:
.replace('replaceBox', storyQuests.check[i]);
(Actually I started with something else that didn't work at all, tried several other ways and eventually gave up and created an additional item in my object to hold the checkbox IDs that that is referencing:
check: ['box0', 'box1', 'box2', 'box3', 'box4', 'box5', 'box6', 'box7', 'box8', 'box9', 'box10', 'box11', 'box12', 'box13', 'box14', 'box15', 'box16', 'box17', 'box18', 'box19', 'box20', 'box21', 'box22', 'box23', 'box24', 'box25', 'box26', 'box27', 'box28', 'box29', 'box30', 'box31', 'box32', 'box33', 'box34', 'box35', 'box36', 'box37', 'box38', 'box39', 'box40', 'box41', 'box42']
However, even though the .replace works on everything else, on these IDs it doesn't seem to, it stops ALL checkboxes from working and the console shows this error:
GET file:///A:/sites/mysite-com/undefined
net::ERR_FILE_NOT_FOUND
So ultimately, how do I replace the words "replaceBox" with different values, or honestly any other solution to allow each checkbox to be checked independently. I thought about removing any ID at all on the checkboxes but I feel I'll need them in the future as I plan on making a way for people to login and have it save the checked state of each card.
EDIT 1:
The mainCardHTML code:
var mainCardHTML = "<div class='col hide-on-small-only m3'> </div>" +
"<div class='col s6'>" +
"<h5 class='header xvred-text'id='replaceMe'>%questName%</h5>" +
"<h6 class='header xvblue-text'id='replaceMe'>%questChapter%</h6>" +
"<div class='card horizontal hoverable'>" +
"<div class=card-image><img id='replaceMe' src=%questImg%></div>" +
"<div class='card-stacked xvred'>" +
"<div class='card-content xvblue'>" +
"<p id='replaceMe'>%questDescription%" +
"</div>" +
"<div class=card-action>" +
"<form action=#>" +
"<p><input id='replaceBox' type=checkbox>" +
"<label class=white-text for='replaceBox'>Complete!</label>" +
"</form>" +
"</div>" +
"</div>" +
"</div>" +
"</div>" +
"<div class='col hide-on-small-only m3'> </div>"
The storyQuests object(The actual object is way to long to post here for readability so I replaced the strings):
var storyQuests = {
name: ["43 strings", "43 strings", "..."],
chapter: [43 numbers, 43 numbers, ...],
img: ["43 strings", "43 strings", "..."],
description: ["43 strings", "43 strings", "..."]
check: ["box0", "box1", "..."]
}
First a little note, review the HTML code of mainCardHTML, there are two <p> elements unclosed (no </p>) and some of the html attributes don't have the ' in their values.
In your storyQuests object, you don't have the comma before the check field. It's probably a typo pasting the code in the question, but verify it.
Javascript function replace by default only replace the first appearance of the word. In your case, you have two replaceBox on each card, so you should use...
.replace(/replaceBox/g, storyQuests.check[i]
With all this, your replacement code works without problem in fiddle...
https://fiddle.jshell.net/rigobauer/v8erbuur/

Getting variable into JS via PHP assigned id

I have the following Javascript to generate a silent call to another sheet to update a database value without refreshing the page
function UpdateDB(table,column,type){
var value = $("#Assigned").val();
$.post("UpdateValuation.php?Table=" + table + "&Value=" + value + "&Column=" + column + "&Type=" + type, {}).done();
};
This works perfectly but only for the "Assigned" table row since it is statically assigned.
I use the following php to generate the table entry with button
print "<tr><td>" . $stuff['Status'] . "</td><td ><input type=\"text\" id=\"" . $stuff['Status'] . "\" name=\"" . $stuff['Status'] . "\" value=". $stuff['Value'] ." size = \"4\" style = \"text-align: center\"/><button onclick=\"UpdateDB('NOCstatus','Status','". $stuff['Status'] ."');\">Update</button></td></tr>";
Which after variables are assigned looks like this for my "Pending" row
<input id="Pending" type="text" style="text-align: center" size="4" value="120" name="Pending"> </input>
<button onclick="UpdateDB('NOCstatus','Status','Pending');">
Update
</button>
My problem is that passing "this.value" or trying to use a variable in the javascript portion I always come up with a blank value, the only time I can get a value to be correct is by statically assigning the "#Assigned" or "#Pending" in the value field. I have hundreds of entries so I don't want to write the function over for each of these. I know there is probably something extremely simple I am missing but I cannot get the pieces to fit.
I need to pass the typed in value in the input field to the function to update the database. Please help.
function UpdateDB(table,column,type){
var value = $('#'+type).val();
$.post("UpdateValuation.php?Table=" + table + "&Value=" + value + "&Column=" + column + "&Type=" + type, {}).done();
};
?

Add a "new line" in innerHTML

I am trying to create a table with images in first cell and information about the pic in second cell.
I need to add different information in one cell, like that:
cellTwo.innerHTML = arr_title[element] + arr_tags[element];
Is it possible to add a "new line" there?
I mean like that:
cellTwo.innerHTML = arr_title[element] + "/n" + arr_tags[element];
The simplest way is by adding a line break as html
cellTwo.innerHTML = arr_title[element] + "<br />" + arr_tags[element];
If you want your newlines to be treated literally, you could use the <pre> tag
cellTwo.innerHTML =
"<pre>" + arr_title[element] + "\n" + arr_tags[element] + "</pre>";
To round out your understanding:
Since it is html (innerHTML) it renders html and you can use any html you wish, so in this case simply add an good old fashioned <br>:
var test = document.getElementById('someElementId');
test.innerHTML = "The answer <br>to life, the universe, and everything...<br> is 42.";
If it were a string, such as in an alert box or text box etc. then /n would be correct:
alert('Never /n Forget your towel.');
Happy Coding!
- $cr1ptN!nj#
No, <br /> does not work in asp .net but you can instead write it like so
cellTwo.innerHTML = arr_title[element] + arr_tags[element]; arr_title[element] + "/n" + arr_tags[element];
Edit - alternative wrapped in code tags
cellTwo.innerHTML = arr_title[element] + arr_tags[element];
cellTwo.innerHTML += arr_title[element] + "/n" + arr_tags[element];
Semicolon ";" seems to act as line breaks
Remember the "+=" to assign multiple values to the string

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