javascript Firebug error: Identifier starts immediately after numeric literal - javascript

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.

Related

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

div text to input value

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 );

jquery function adding html form with returns

I have a US map and when someone clicks on a state it displays a form. For example like below... this is a sample. The problem is a few of the forms have over 15 form elements. Adding those without returns is not manageable and very tedious to add without getting errors.
Is there anyway I can add a form to the code below and add the form with returns instead of without returns like the code below?
No Returns = I mean adding each form element on one line without pressing enter on your keyboard ...
Returns = Adding form element then pressing enter to go to the next line.
function myCallback(event, data)
{
if ('CA' == data.name)
{
$('#notif').html('<form>First name: <input type=\"text\" name=\"name\" value=\" "+ data.name +" \"><br>Email: <input type=\"text\" name=\"email\" value=\" "+ data.email +" \"></form>');
}
Your question is a bit unclear but you can use basically two ways
1. String manipulation
In javascript there are two ways to break a long string, concatenation and using the \ character.
Example
Concatenation:
$('#notif').html(
'<form>First name: ' +
'<input type="text" name="name" value="' + data.name + '"\>' +
'<br>Email:' +
'<input type="text" name="email" value="'+ data.email +'"\>'+
'</form>');
Basically you organize your strings to be more readable. Mind the use of ' and " they can be used indistinctly but is better if you are consistent in which sign you use to enclose your strings and which to use for your attributes.
Breaking long strings
The docs says that you can break a long string with a \ sign
Example
$('#notif').html(
'<form>First name: \
<input type="text" name="name" value="' + data.name + '"\>\
<br>Email:\
<input type="text" name="email" value="'+ data.email +'"\>\
</form>');
Is a bit harder to read but basically is the same using only one string.
2. Using native elements
You can also use jquery to create your form elements in a variable and attach them to the form using the append function
Example
Using JQuery
var container = $('#notif');
container.append('<form></form>')
var form = container.children('form');
form.append('First name: ')
.append('<input type="text" name="name" value="' + data.name + '"\>')
.append('<br>Email:')
.append('<input type="text" name="email" value="' + data.email + '"\>');
This function is chainable so you can have one element per line
Here's the answer to "MY" question that's so hard to understand.
Use .load( "form.php" )
$('#notif').load("form.php");

Getting new lines from database to html textarea

I have this code
<script>
var database="<%=rsta2.getString("data").replaceAll("[\\t\\n\\r]","<br />")%>";
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<textarea rows="15" cols="70" name="textbox' + counter + '" id="textbox" >' + database + '</textarea>')
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
</script>
<body>
<div id=TextBoxesGroup>
</div>
</body>
Initially I add data like this
Using the above code gives me
What am I doing wrong?I tried to replace <br /> with &#xA ,I get new line but an extra line feed along with it.What should I do so that next line appears?Instead of i want the hello2 to come on next line.
Another query is suppose I have quotes("this is my dog") to retrieve, how should I write it?How should I retrieve the quotes("") cause it throws an error.(UNexpected identifier)
For example <%=rsta2.getString("data").replaceAll("["]","&quot")%>,
I know the above doesnt work,but How should I write it?
Check this ,
html('<textarea rows="15" cols="70" name="textbox' + counter + '" id="textbox" >' + database + '</textarea>
Have you closed this statement properly ?
Also please more clear in the second part , cant get what you saying?
Another query is suppose I have quotes to retrieve, how should I write it? For example <%=rsta2.getString("data").replaceAll("["]","&quot")%> I know the above doesnt work,but How should I write it?

JavaScript not replacing all elements

I'm trying replace the index of form elements. I have the following
var test = "<input name='[1].Id' value='598' type='hidden' /><input name='[1].OrderItemId' value='867' type='hidden' />";
alert(test.replace('[1]', '[2]'));
I'm getting curious results. The first hidden field is replaced by the second is ignored
ie my response is something like this:
"<input name='[1].Id' value='598' type='hidden' /><input name='[2].OrderItemId' value='867' type='hidden' />"
EDIT:
OK, thanks these methods worked on my simple example. However in reality my string is a bit more complex. Here is the contents of "var lastRow "
<td>
<a class="deleteAddress" href="#">
<img alt="remove" src="/images/icons/delete_button.gif">
</a></td>
<td class="p-5" width="100">
<input name="[1].Id" value="612" type="hidden">
<input name="[1].OrderItemId" value="868" type="hidden">
<input class="itemAddressQuantity" name="[1].Quantity" value="" type="text">
</td>
<td class="p-5" width="100">
<select name="[1].AddressId"><option value="2">address1</option></select>
</td>
and here is the js function
$('#addNewAddress').click(function (event) {
event.preventDefault();
var length = $('.table-item-address tbody').find('tr').length;
var previousLength = length - 1;
var previousIndex = "/\[" + previousLength + "\]/g";
var currentIndex = "[" + length + "]";
var lastRow = $('.table-item-address tbody tr').last();
alert(lastRow.html()); // html is shown above
var newRow = lastRow.html().replace(previousIndex, currentIndex);
$('.table-item-address tr').last().after('<tr>' + newRow + '</tr>');
AdjustValues();
});
In JavaScript, passing a string as the first parameter to replace() will only replace the first occurrence. You need to use a regex, with the global flag:
test.replace(/\[1\]/g, '[2]');
The extra backslashes (\) escape the brackets ([ and ]).
Edit: responding to the OP's edit, if you want to dynamically build a regex, you can't use a regex literal - that's the thing delimited by forward slashes (/), not quotes (") as in your edit. You're passing a string into replace(), I'm passing in a regex literal. Use the JavaScript RegExp() constructor to fix yours:
// The first argument is the regex, the second is a string of flags.
var previousIndex = new RegExp("\\[" + previousLength + "\\]", "g");
// Then, it's exactly the same as before.
// The second argument to replace is still a string.
var newRow = lastRow.html().replace(previousIndex, currentIndex);
Note the difference in character escaping.
See here: http://www.w3schools.com/jsref/jsref_replace.asp
Check the 3rd sample where they talk about global replace
change the replace to this replace(/[1]/g, '[2]');
This does a global replace. However I'm not sure [] and . are legal characters for ids/names.

Categories

Resources