I figured it out using the /=on/g global value and it worked there... Thanks for the help ^_^
Any other advice is appreciated though! :D
I currently am having difficulty trying to figure out where to put the formdata.Replace to remove all =on tags after output from my form.
I have multiple check boxes, the ones that are submitted go to the next page and it displays all the inputted data. However, it also keeps the =on tag from the javascript and I can only figure how to remove one of them. I'm assuming I need to input another loop somewhere, but I am confused as to how to do that since there is an unknown number of checkboxes they can choose at one time (this output is being used on multiple pages, and there's different numbers of checkboxes per page).
This is the original script I found:
<script type="text/javascript">
<!-- HIDE FROM INCOMPATIBLE BROWSERS
if (window != top)
top.location.href=location.href
document.write("<h1>Your form has been submitted!</h1><h2>You entered the following data:</h2>");
var formData = location.search;
formData = formData.substring(1, formData.length);
while (formData.indexOf("+") != -1) {
formData = formData.replace("+", " ");
}
formData = unescape(formData);
var formArray = formData.split("&");
for (var i=0; i < formArray.length; ++i) {
document.writeln(formArray[i] + "<br />");
}
// STOP HIDING FROM INCOMPATIBLE BROWSERS -->
</script>
I added formData = formData.replace("=on", " "); in the while loop, which removes the first one but not any of the other ones. I am not sure where to put it, however.
You'll want to be careful with that code, unless you don't expect user-generated input, as you may end up replacing something that you didn't want to. There are a few JS libraries that will pull out the submitted values for you in a much safer way that you may want to research.
The issue that you're encountering is that it will only replace "=on" as many times as it replaces "+" with " ". If you add an additional while-loop, you can replace "=on" until they're all gone.
while (formData.indexOf("+") != -1) {
formData = formData.replace("+", " ");
}
while (formData.indexOf("=on") != -1) {
formData = formData.replace("=on", "");
}
Related
I'm currently working in user creation login page for an e-commerce and I need to achieve something like this: https://drive.google.com/file/d/1JJBeZG-oyzrh8vCDRMjfv03oGDjrWwZw/view?usp=sharing (The video has to be seen on fullscreen, otherwise it'll be too small to detail anything)
Thing is I should not allow any special characters when the form is submitted and I think I already solved that:
$('#login_form #document').on('input', function() {
this.value = this.value.toLocaleUpperCase();
let count = this.selectionStart,
regex = /[^a-z0-9]/gi,
value = $(this).val();
console.log(value)
if(regex.test(value)) {
$(this).val(value.replace(regex, ''));
count--;
}
this.setSelectionRange(count, count);
});
But I can't really think in a way to show the dots and hyphens and not allowing them on submit.
Also, any recommendation to improve the code will be well receive. Thanks in advance!
Just keep the formatting from your front-end, do some reverse reformatting in backend instead, example you input 10,000.00 then you submit it using backend PHP just replace "," str_replace(',', '', '10,000.00') then you will get 10000.00 then use $new_number = (float)10000.00
$input_number = '10,000.00';
$input_number_no_comma = str_replace(',', '', $input_number);
$input_number_new = (float)$input_number_no_comma;
echo $input_number_new ;
Hi everyone i have one problem with my ajax tag search system. Following code working fine just one searching tag. But if i search multiple tag then it is not working. What i need to do here? What i am missing anyone can help me here ?
For example: When i write #innovation the the ajax will showing #innovation but when i search multiple tag like #innovation asking #stackoverflow then it is not searching #stackoverflow
$(document).ready(function() {
var start=/#/ig;
var word=/#(\w+)/ig;
$("#contentbox").live("keyup",function() {
var content=$(this).text();
var go= content.match(start);
var name= content.match(word);
var dataString = 'searchword='+ name;
if(go!==null && go.length!==0) {
$("#msgbox").slideDown('show');
$("#display").slideUp('show');
$("#msgbox").html("Type the name of someone or something...");
if(name!==null && name.length!==0) {
$.ajax({
type: "POST",
url: "boxsearch.php",
data: dataString,
cache: false,
success: function(html) {
$("#msgbox").hide();
$("#display").html(html).show();
}
});
}
}
return false;
});
});
I think the problem is the following line :
var start=/#/ig;
var word=/#(\w+)/ig;
There's a million different ways to crack this nut. One of the methods I used in the past was to send the whole input as a single attribute on the service call, and then pass it into db call (via PHP) using the REGEX feature of MySQL. Using that feature, it searched for any combination of value 1, or value 2 or value 1 and value 2, etc.
But let's attack it from the front end as you're doing. You have an input coming in as a combination of "#word1 #word2". So rather than doing regex summersaults to find the beginning and the end, how about simplifying things and doing a string.split() on the "#" character. You can take the resulting array of values, loop to create your service call string (don't forget to trim blank spaces) and send the call off.
The problem is definetely coming from your regex. The second you write a second word in your textarea (I'm assuming you're using a textarea), the if condition fails.
I'm not regex expert, however I have a js solution:
var keywords = $(this).val().split(' ').trim();
Get all the keywords this way, then loop through each one and check if it's a correct tag.
var obj = [];
keywords.forEach(function (content) {
var go = content.match(start);
var name = content.match(word);
//check to see if the searchword is valid.
//If it is we add it to the list and continue the loop.
//If not we ignore it and continue the loop.
//If you want to stop the loop when one searchword is wrong add "return false;"
if(go !== null && go.length > 0 && name !== null && name.length > 0 ){
obj.push(name);
}
});
if(obj.length > 0){
var dataString = JSON.stringify(obj);
//do ajax call here
}
I'm also assuming you're sending all your searchwords at once to your php file.
EDIT: Pushing all valid keywords into an array obj that will be later parsed as a JSON string.
Bit of background info - the developer of the system we use has left the company and I've been asked to add a few new features. Needless to say, there's no documentation and to make matters worse I'm an absolute novice so am having to learn as I go along. I'm kind of managing to do most things but have come totally stuck on this problem. For anyone kind enough to help me out, if you could really dumb any answers down that would be great. So, the problem........
HTML page that is dynamically populated with a list of items. For each item in the list there's a checkbox, and for each checkbox that's ticked I need to update a MySQL database. The code that adds the checkboxes to the page is
echo("<td class=\"tableRight\" style=\"width: 5%\"><input type=\"checkbox\" name=\"costume[]\" value=\"".$costume['id']."\" id=\"costume_".$costume['id']."\" onclick=\"tickrow(".$costume['id'].");\" /></td>");
The JavaScript file is loaded in the page head with
<script src=\"costume-list.js\" type=\"text/javascript\"></script>
The button's code that should kick off the database update is
echo("<div class=\"navContainer\" onClick=\"batch_move() \" class=\"navItem\">");
echo("<img src=\"/resource/img/icon/move.png\" border=\"0\" /><br />Batch Move Costumes");
echo("</a></div>");
And finally the JavaScript I've managed to put together is
function batch_move() {
var combo = document.getElementById("cbo_title");
var move_to = combo.options[combo.selectedIndex].text;
var move_to_id = combo.options[combo.selectedIndex].value;
if (move_to.length==0) {
alert("Please select the location you want to move the costumes to.");
return;
}
var resp_move = confirm("Are you sure you want to MOVE the selected costumes to "+move_to+" ?");
if (resp_move==true) {
alert("Lets move em");
window.open ("http://path-to-server/costume/batch-move-costume.php? loc="+move_to_id+"&items="+INeedTheArrayHere,"mywindow","menubar=1,resizable=1,width=350,height=250");
}
}
So what I want to do is first make sure that at least one checkbox is ticked and if it is then get the values of the ticked boxes into an array to pass to the called PHP form. I can manage the update code in the opened form, it's just getting the array to it.
Sorry for long post, but hope that's enough info. If there's anything else you need to know please ask and I'll supply more details. Many thanks
First off, you have my deepest sympathy. It totally sucks to get something like this mess dumped on you. This should help:
var valString = "";
var list = document.querySelectorAll('input[type ="checkbox"]');
for(var node in list) {
if(list[node].checked) {
valString += list[node].name + ',';
//you will need to add a name property when you create the html
//<input type='checkbox' name='dress'>Dress
}
}
This will create a comma-delimited string of all the checked checkbox values that you can send to the server. You can split it into an array on the server side. You will not be able to just drop an array into the GET part of the url like you have 'IneedArrayHere' above, hence the string. Also, if there are too many selections (URLS have a length limit) you will need to switch from GET to POST, which is a whole other issue.
P.S. I highly recommend that you take all those escaped double quotes and make them unescaped single quotes. That sort of thing is done by people who are used to things like SQL varieties where the difference between single and double quotes is significant, but in javascript and most (all?) sever-side languages (like php) the difference is irrelevant.
<script>
function myFunction()
{
var collection =document.getElementById("boxes").getElementsByTagName('INPUT');
var res =[];
for (var x=0; x < collection.length; x++) {
if (collection[x].type.toUpperCase()=='CHECKBOX')
var b = [collection[x].name ,collection[x].checked ] ;
res[res.length] = b;
}
alert(JSON.stringify(res));
}
</script>
<html>
<div id="boxes">
<input type="checkbox" name="1" value="1">eded</input>
<input type="checkbox" name="2" value="2">eded</input>
</div>
<input type="button" onclick="myFunction()" value="ok">
<html>
Now you can simply send the JSON to the server.
many thanks for your answer. I've plugged in your code into the JavaScript and ticked a few of the checkboxes on the form. When the code runs I get the first prompt message, but not the message box with a the value of valString ?.
It's obviously something I'm doing wrong - as I said I'm a complete novice and struggling to get to grips with this system I seem to have inherited (not through choice!)
Current code looks like this, and any pointers to my latest mistake would be much appreciated
function batch_move() {
var combo = document.getElementById("cbo_title");
var move_to = combo.options[combo.selectedIndex].text;
var move_to_id = combo.options[combo.selectedIndex].value;
if (move_to.length==0) {
alert("Please select the location you want to move the costumes to.");
return;
}
var resp_move = confirm("Are you sure you want to MOVE the selected costumes to "+move_to+" ?");
var valString = "";
var list = document.querySelectorAll('input[type ="checkbox"]');
for(var node in list) {
if(list[node].checked) {
valString += list[node].name + ',';
}
}
alert(valString);
if (resp_move==true) {
alert("Lets move em");
window.open ("http://path-to-server/costume/batch-move-costume.php?loc="+move_to_id+"&items=2,3,4,5","mywindow","menubar=1,resizable=1,width=350,height=250");
}
}
<form>
<input name="Team1" id="team1" type="text" value="Team1?">
<button id="dostuff" value="Go">Go</button>
</form>
<div id ="nicteamcolumn">Team: </div>
<script>
$('#dostuff').click(function(e) {
var team1 = $('input[name="Team1"]').val();
if (typeof(Storage) !== "undefined") {
if (localStorage.teamlist) {
localStorage.teamlist= localStorage.teamlist + team1;
}
else {
localStorage.teamlist = " ";
}
$('#nicteamcolumn').html("Team:" + "<br>" + localStorage.teamlist + "<br>")
}
}
</script>
Basically, when the button is clicked, I am taking the input from Team1, add it to localStorage.teamlist, and changing the html of #nicteamcolumn to localStorage.teamlist
I am getting a weird output the first time I click the button. It prints the value for team 1 a ton of times over and over. The 2nd click and on seem to be working fine as well as when I close the page and coming back and keep adding to the list.
Any help would be greatly appreciated?
It prints the value for team 1 a ton of times over and over. The 2nd click and on seem to be working
That's because the localStorage object is persistent. Even when the source code of your script changes, the localStorage values will still exist. You might be confusing localStorage with sessionStorage.
Fixing your code:
Fix the syntax error by placing a ); after the last }.
typeof is not a function, please do not make it look like one, by removing the parentheses.
The very first time, nothing will print, because you're adding a space instead of the value of Team1.
Instead of setting the property directly, it is recommended to use the .getItem and .setItem methods, to avoid mistakes as using conflicting key names.
Your current "list" is a set of a concatenated string. That's not easily maintainable. Either use an unique separator to separate your values, or use JSON.stringify and JSON.parse to store real arrays.
Demo: http://jsfiddle.net/BXSGj/
Code (using JSON):
$('#dostuff').click(function(e) {
e.preventDefault(); // Prevent the form from submitting
var team1 = $('input[name="Team1"]').val();
if (typeof Storage !== "undefined") {
// Will always show an array:
var teamlist = JSON.parse(localStorage.getItem('teamlist') || '[]');
teamlist.push(team1);
localStorage.setItem('teamlist', JSON.stringify(teamlist));
$('#nicteamcolumn').html("Team:<br>" + teamlist.join('<br>') + "<br>");
}
});
Using a separator (only showing different lines):
var SEP = '|'; // Separator example
var teamlist = (localStorage.getItem('teamlist') || '').split(SEP);
teamlist.push(team1); // Still the same
localStorage.setItem('teamlist', teamlist.join(SEP));
To remove the stored items, use the localStorage.removeItem method:
localStorage.removeItem('teamlist');
See also: Compability table for the Storage object.
I need a javascript bookmarklet which can click on a button. The thing is, there are 100+ buttons on the page all with the same value. The name is unique but quite long.
The full name of the element is something like :
actions[http://apps.facebook.com/frontierville/giftaccept.php?next=giftaccept.php&senderId=1%3A1325206719&gh=3a8bfdace76051752a9127d1f9b43872&gift=nails×tamp=1285598414&ref=tab&key=29b15e06ed9d7c00a8870c955ab938cf%24%24cfH1PUUZ%217bZYhg8M-o-XQc%218HHRMcvvyhuf4d%21.64qEvlQe&src=request&aff=gift&crt=nails&signature=6dd3fa03fe88f98b6dcab4faf4c7da94]
The value of every button is Accept and Play.
So. Is there a way to have it click on the button with a specific URL in the name?
Here is the source of the info for one of the buttons (got this from chrome's inspect element feature):
<input value="Accept and Play" type="submit" name="actions[http://apps.facebook.com/onthefarm/giftaccept.php?senderId=1259413693&gift=mysterygift×tamp=1285599906&ref=gift_accept_tab&key=78fcc7de3b36b8f9564262fab506893f%24%24ceK5RVRY61bZYhg8M-o-XQcyL%2CzHccEwEeuj4e-%21-dh0AD0A2AgyScd&signature=32db959ce43f8330cf8fd992fbd53a51&srcapp=FarmVille]">
This should do it...
javascript:var nam=prompt("Give me a URL to look for"); nam="actions["+nam.replace(/\&/g, "&")+"]"; var els=document.getElementsByName(nam); if(els.length == 0) alert("Button not found"); else els[0].click();
It's based on getElementsByName, here it is all spelled out...
var nam = prompt("Give me a URL to look for");
nam = "actions[" + nam.replace(/\&/g, "&") + "]";
var els = document.getElementsByName(nam);
if(els.length == 0)
alert("Button not found");
else
els[0].click();
Here's a rough example of what you might want to do.
var url = 'http://reallylong.facebook.url.from.your.example';
var searchName = 'actions[' + url + ']';
var items = document.getElementsByName(searchName);
if (items.length > 0) {
var myButton = items[0]; // assuming the first item is the correct one
myButton.click(); // programmatically click it
}
if the url is going to change every time, you can find someway to fill the url variable, and use that to generate the element name. This example assumes that element is the only one on the page with that exact name attribute.
This example is pretty rigid and may not work as your bookmarklet if you need to interact with it. What do the other elements look like? Would it be better to look for an element pointing to the giftaccept url or something like that? The script would have a lot more flexibility in a situation like that.
For convenience and compatibility use JQuery selectors:
nameVal = 'actions[http://apps.facebook.com/onthefarm/giftaccept.php?senderId=1259413693&gift=mysterygift×tamp=1285599906&ref=gift_accept_tab&key=78fcc7de3b36b8f9564262fab506893f%24%24ceK5RVRY61bZYhg8M-o-XQcyL%2CzHccEwEeuj4e-%21-dh0AD0A2AgyScd&signature=32db959ce43f8330cf8fd992fbd53a51&srcapp=FarmVille]'
$("input[value='Accept and Play'][name='" + nameVal + "']").click()