JS Slice() doesn't work properly - javascript

I am trying to remove the last characters from the following html code
<tbody><tr><tr>1<td><label for='depart1'>Department 1</label><br /><input type='text' id='depart1' class='textbox large' value='IT' /><br><label for='Courses_for_depart1'>Course for Department 1</label><br /><textarea id='Courses_for_depart1' class='textarea large' >OS</textarea></td></tr></tbody>
with the following code
addHtml.slice(0,-13);
It should remove </tr></tbody> But it removes only ></tbody>
how to get rid of this strange behavior.
update
addHtml=$("#departments").html();
<table id="departments">
<tbody><tr><tr>1<td><label for='depart1'>Department 1</label><br /><input type='text' id='depart1' class='textbox large' value='IT' /><br><label for='Courses_for_depart1'>Course for Department 1</label><br /><textarea id='Courses_for_depart1' class='textarea large' >OS</textarea></td></tr></tbody> </table>
The above snippet is copied form view source code of chrome.

There are probably white space between the closing </tbody> tag and the </tr> tag. Try something like this:
addHtml = addHtml.trim();
var tbody = '</tbody>';
var t1 = addHtml.indexOf(tbody)+tbody.length;
var t2 = addHtml.lastIndexOf('</tr>');
var len = t1-t2;
var newString = addHtml.slice(0,-len); // This will have the string without the </tr> </tbody>

Since your addHTML contains spaces at the end and the beginning, so you need to trim all the spaces at start and end before using slice function so use
$.trim(addHtml).slice(0,-13);
Working demo

As a possibly safer alternative, you could do this in two steps:
1) find the last </tbody> in the string, then slice up to it.
2) find the last </tr> in the remaining string, then slice up to that.
String.prototype.lastIndexOf()

Related

how to use split() function in classic ASP for mass inputs textbox?

I am trying to use the split function in classic ASP using JavaScript. I need to have a big text box where I can keep group of bar-code numbers of products. Once submit button is clicked These bar-code numbers needed to be split by each and every character term for all bar-code numbers (in a loop). For instance, if i have 5 bar-code numbers, I have to split first bar-code number by each and every character/number, keep into array and continue same process to all 5 bar-code numbers. I wanted to display the result of split-ted numbers into a paragraph for myself just to check if its working. Below is the code I was working on. It doesn't show me anything when i click the button. I am not being able to figure out my logical error or what am I missing. How do I fix it? I didn't find any helpful solution when i was doing research.
<p id="demo"></p>
<form name="submitticket" action="<%=Request("script_name")%>" method="post">
<input type="hidden" name="action" value="sendform">
<table cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td align="center" colspan="2">
<br /><textarea name="noskews" id="skewsip" rows="50" cols="100" wrap="soft" maxlength="5000"><%=Request("noskews")%></textarea>
</td>
</tr>
<tr>
<td align="center" colspan="2" style="padding-top:20px;">
<input type="submit" name="clearNoskew" value="Submit" class="a-t-button-mini">
</td>
</tr>
</table>
</form>
<script>
$("form").on("click", ".a-t-button-mini", function(event){
//var clickedId = $(this).attr('value')+','; // give me first numbers,
var locationBtn = $('#skewsip'); // Select the input
var locationBtnValue = $('#skewsip').val(); // Take the select value
var ids = locationBtnValue.split(',');
document.getElementById("demo").innerHTML = ids; //want to display in a paragraph for myself
});
</script>
I was able to split one barcode (out of total 5 barcodes entered inside textarea) by every characters and display it into div. for example: I entered 5465 8989 7586 5236 5486 (These barcodes are entered using "enter or new line" after every 4 numbers; space in above example means the next barcode is in next line). I get split output of (5,4,6,5) which I need but it didn't give me for rest of my barcodes. In other words, I couldn't do same for all 5 total bar codes entered into the textarea/textbox. I know its only "for loop" When I kept for loop in my code, it executes for first barcode out of 5 barcodes.
<script>
$("#form").on("click",".a-t-button-mini", function(event){
var locationBtnValue = $('#skewsip').val();
var skews_array = locationBtnValue.split("",12);
// for (i = 0; i < locationBtnValue.length; i++) {
// text += skews_array[i] + "<br>";
document.getElementById("test").innerHTML = skews_array;
// }
});
</script>
I think you're saying each barcode on a new line of the textarea. If so, this should work for you (\n is the newline character), at least to capture and re-output to the demo element:
<script>
$("form").on("click", ".a-t-button-mini", function(event){
var ids = $("#noskews").val().split('\n');
$.each( ids, function( index, value ) {
$("#demo").append(index + ' - ' + value + '<br/>');
});
});
</script>
Added working code to codepen:
http://codepen.io/anon/pen/NxENYW

jQuery change number inside a name attribute

I'm writing some JavaScript to clone a table row containing form elements.
It's working well so far but there's one piece I can't quite figure out.
The element names have a number which increases with every row.
E.g:
<table>
<tbody>
<tr>
<td><input type="text" name="name[0][abc]" /></td>
<td><button class="add-row-button">+</button></td>
</tr>
<tr>
<td><input type="text" name="name[1][abc]" /></td>
<td><button class="add-row-button">+</button></td>
</tr>
</tbody>
</table>
I need the cloned row to update the number. There are multiple fields in each row which need this updated number so I can't just include the new name in the jQuery code. What I think has to happen is I need get the name, use a regex replace, then update the attribute.
Here's my current (simplified for the example) jQuery:
// Current num of elements. Names are 0 based so this will be the number used
// for the new name.
var formRowCount = $('table tr').length;
$('.add-row-button').click(function() {
// Clone the last row.
$(this).closest('tr').last().clone().insertAfter($(this).closest('tr'));
// Set the new field selector.
var $newRow = $(this).closest('tr').next();
$newRow.find('input[type="text"]').val('');
formRowCount++;
});
Can someone point me in the right direction. Before formRowCount++; I need to get the current element name and update the number with formRowCount.
Yeah, you can use regex if you want.
var formRowCount = $('table tr').length;
$('.add-row-button').click(function() {
// Clone the last row and insert it.
$(this).closest('tr').last().clone().insertAfter($(this).closest('tr'));
// Select the input field
var $newInput = $(this).closest('tr').next().find('input[type="text"]');
// Update the input value and name attribute
var newName = $newInput.attr('name').replace(/^(name\[)\d+(\].+)$/, '$1' + formRowCount + '$2');
$newInput.val('').attr('name', newName);
// Update the number
formRowCount++;
});

Using jQuery to create a number of input fields, based on value entered

I have a form in which I ask the user how many file inputs they need, and I'd like to generate the suitable number of file browsing inputs dynamically based on the answer.
Here is my attempt:
$("#howmany").change(function()
{
var htmlString = "";
var len = $(this).val();
for (var i = 0; i <= len; i++)
{
htmlString += "
<tr>
<td>
<input name="ufile[]" type="file" id="ufile[]" size="50" />
</td>
</tr>
";
}
$("#dynamic_upload").html(htmlString);
}
HTML
<input id="howmany" />
<table id="dynamic_upload">
</table>
The idea being that repeating "units" of inputs will be generated based on the number entered.
But it isn't working, any idea where I'm going wrong?
EDIT: More clarity on "it isn't working" (apologies). When I include this code, after entering the number into the field "howmany" there is no visable reaction. No error messages appear, although - is there an error log somewhere I don't know how to read? (new to this)
It's not possible to create a string like that. Try:
htmlString += "<tr>";
htmlString += "<td>";
htmlString += '<input name="ufile[]" type="file" id="ufile[]" size="50" />';
htmlString += "</td>";
htmlString += "</tr>";
Also remember you need to use single quotes around the string if it contains double quotes, or escape them.
You are also missing ); from the end of the function:
$("#dynamic_upload").html(htmlString);
} <--- this should be });
You can't have newlines in JavaScript strings. Moreover, you are using double-quotes within the string (i.e. for the <input> attributes). Possible rewrite:
htmlString += '<tr><td><input name="ufile[]" type="file" id="ufile[]" size="50"></td></tr>';
In the future, please give a more descriptive problem than "it isn't working" -- for example, do you get any error messages?

On keypress event, how do I change a ',' to a '~'

I have to prevent Coldfusion's default list delimiter ',' from being entered into a form input array. I am new to using javascript for validation purposes, and have never tried to switch out the values someone is typing in. How can I snag a comma, and replace it with a tilda?
Javascript i've tried so far:
$(document).ready(function(event){
var regExComma = /,/;
$("[name='name[]']").live("keypress",function(event){
// i know i could check the numerical value, i feel this requirement can get more added to it and I would like to just change the regEx accordingly.
if(regExComma.test(String.fromCharCode(event.which)){
//it was a ',' switch it to '~'
event.which = 126;
}
});
// added to show that the 'name' input form array is the only input that cares about the ','
var regExDig = /[\d]/
$("[name=min[]],[name=max[]]").live(keypress, function(event){
if(!regExDig .test(String.fromCharCode(event.which)){
event.preventDefault();
$("#cfocFormMessages").trigger("updateMessages", {"url":"components.cfc/CFOC.cfc", "data":{"more":"stuff"}});
}
});
});
cfml / html involved:
<form action="components/CatagoryService.cfc?method=saveVersion">
<input id="version" name="version" type="text">
<!--- .. more inputs ..--->
<table id="table">
<thead><tr><th>name col</th>
<th>min col</th>
<th>max col</th>
<th>edit</th>
</tr></thead>
<tfoot></tfoot>
<cfoutput query="variables.query">
<tr><td><input name="name[]" type="text" value="#variables.query.name#"></td>
<td><input name="min[]" type="text" value="#variables.query.min#"></td>
<td><input name="max[]" type="text" value="#variables.query.max#"></td>
<td><input name="id[]" type="hidden" value="#variables.query.id#">
edit</td>
</tr>
</cfoutput>
<tr><td></td><td></td><td>add</td></td></tr>
</table>
<input type="Submit"/>
</form>
if I alter CatagoryService.cfc?method=saveVersion to <cfreturn arguments> in a JSON string, a typical response from Coldfusion looks like:
{VERSION:"",name:"name1,name2",min:"1,3", max:"2,4",id:"1,2"}
I put your HTML on jsfiddle (you can test it there) and added this JavaScript, using a selector that matches all and elements:
$(document).ready(function(event){
$(document).delegate("input, textarea", "keyup", function(event){
if(event.which === 188) {
var cleanedValue = $(this).val().replace(",","~");
$(this).val(cleanedValue);
}
});
});
All commas in the value string are replaced by a tilde if a comma (code 188) was entered.
Remember that JavaScript validation is nothing you want to rely on. The commas can easily be send to the server or never get replaced, e.g. in a user agent with JavaScript disabled.
I replaced the name[] .live() event.which = 126; to event.originalEvent.keyCode=126;
var regExComma = /,/;
$("[name='name[]']").live("keypress",function(event){
if(regExComma.test(String.fromCharCode(event.which)){
//this line works as expected. and will swap out the value on keypress.
if(event.originalEvent.keyCode){
event.originalEvent.keyCode=126;
}else if(event.originalEvent.charCode){
event.originalEvent.charCode=126;
}
}
});
wolfram I upped your keyUp solution as well.
Imho, there's no need to check those keyCodes:
$(document).ready(function(event){
$('#fieldName').keyup(function(event) {
var cleanedValue = $(this).val().replace(",","~");
$(this).val(cleanedValue);
});
});
Check it on jsFiddle.

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