Currently I am working on a script that does an authentication job one time for products with factory code to avoid the fake products.
My end goal is:
- Test a user input value if it matches a list of original codes.
- if the input is checked for the first time and matches one of the original codes-list redirects to a specific web page.
- if the user input is checked for the second time and matches before one of the original codes-checked-list display a paragraph.
- if the input is checked and NOT matches show FAKE.
Here what I write so far:
$(document).ready(function(){
var originalCodes = ['123','1234','12345'];
var userInputCode = document.getElementById('userInputCode');
$('form').submit(function(){
var checkedCodes = [];
var i;
for(i=0; i<originalCodes.length; i++){
if (userInputCode.value === originalCodes[i]){
window.location.href = "SomeLinkHere";
checkedCodes.push(i);
if (userInputCode.value === checkedCodes[i]){
$('checked').css('display', 'block');
}
}else{
$('.fake').css('display', 'block');
}
return false;
}
});
});
.fake {display:none;}
.checked{display:none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post">
<p>Product Code: <input type="text" id="userInputCode"></p>
<input type="submit" value="Check" id="submit">
</form>
<h2 class="fake">Your've a Fake product.</h2>
<h2 class="checked">This code was previously authenticated.</h2>
I faced trouble in the loop of originalCodes array the if statement can't check all the values.
Does anyone have an idea?
Thanks in advance.
Four mistakes:
$('.form') means elements with class form, not the form tag. Use $('form') instead.
Once you navigate away with window.location.href = "SomeLinkHere";, the JavaScript state is cleared. You'll need to save the checked codes somewhere more persistent if you want to do that.
You're adding the code to list of checked codes, then seeing if it's there, which it always will be. You need to reverse these.
If the same code is checked multiple times, checkedCodes could eventually get bigger than originalCodes, and then your loop will miss some of them.
Related
I've seen various similar questions posted, but I can't quite seem to get all the pieces together.
I have a really simple form with an option single input field. I'd like to allow the user to input a value to use, but if they don't I want it to use a default, but only on submit.
Here's the HTML and JS I'm working with. This simply grabs the input value and adds it to the button URL. What I need it to do is see if it's blank on submit only and replace it with "NoName"
<script type="text/javascript">
$(document).ready(function(){
$('#button').click(function(e) {
var inputvalue = $("#rep").val();
window.open("https://example.com/"+inputvalue, "_blank");
});
});
</script>
<form id="options">
<p><input type="text" id="rep" name="rep" placeholder="Your Rep ID: " style="width:auto;" value="" /></p>
<p><button type="button" id="button" style="color:white; background-color: blueviolet; border:none; border-radius: 3px;">GO!</button></p>
</form>
The examples and solutions I've seen have it using placeholders, or onBlur events that cause the box to keep changing if they click in or out of it. I'd like this to stay blank, unless they enter something, then the button URL would change based on that alone.
If empty > use default value in the URL and if not empty > use the url+value entered.
The current behavior works fine if something is entered, but if not, it simply goes to the URL (as the current script tells it to)
If I understand you well is as simple as you described: if empty > use default value in the URL and if not empty > use the url+value entered.
just use simple if else, I made small jsfiddle for you.
get the user value
var userValue=$('#rep').val();
then check if user value is null or empty
if(userValue){ }
if it is empty then use default value
$(function(){
$('#button').click(function(){
var myDefault="http://url.com";
var userValue=$('#rep').val();
if(userValue){ location.href=userValue; }
else { //use default
location.href=myDefault; }
});
});
I am stuck. My company is redesigning its website, but I am stuck with trying to jerry-rig a fix for a problem in the old site. I need to use JavaScript or jQuery.
When a form is submitted, a POST key is sent to the server that starts with "selectedItem_" followed by the item ID. The value attached to it is the text from the button, "Buy This". The complete key:value pair looks something like this:
selectedItem_IDME1KEXN_0_0 : "Buy This"
Because the form has several different versions of the same item, whoever programmed this put several buttons on the form, each with this kind of key. So there may be up to 4 or 5 buttons that are nearly identical. The values assigned to the them are the actualy price, like this:
selectedItem_IDME1KEXN_0_0 : 93.95
selectedItem_IDME2KEXN_0_0 : 99.95
selectedItem_IDME3KEXN_0_0 : 114.95
selectedItem_IDME4KEXN_0_0 : 119.95
All of these are getting sent to the server, which is causing the server to sometimes choose the wrong value. (And I have no idea why it was programmed like this, I am just trying to deal with it!)
MY QUESTION:
How can I use JavaScript or jQuery to evaluate what is currently stored in the POST before it is sent to the server? I would love to iterate through the keys that start with "selectedItem_" and pull out any bad ones before it is sent on its way.
You can bind an event to the submit event of the form, and look at the data.
var $form = $('form').first();
$form.on('submit', function(e) {
e.preventDefault();
console.log( $form.serializeArray() );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" action="">
<input type="text" name="key1" />
<input type="text" name="key2" />
<input type="submit" />
</form>
If all data are from input tags your form, then try something like this:
document.querySelector('form').addEventListener('submit', function (e) {
var input = document.querySelectorAll('input[name^="selectedItem_IDME"]');
var valid = true;
for (var i = 0; i < input.length; i++) {
var item = input[i];
if (Number(item.value) === 93.95) {
valid = false;
e.preventDefault();
}
}
});
I'm working on a donation form that has a widget embedded in it. The widget opts users into our Mobile Giving giving program which uses separate software than our donation forms. I've been asked to see if we can make the widget invisible but transfer the form data to it and submit it when the user submits the donation form. I've already run into a problem with getting the form data to transfer to the widget though.
The form should get the donors first name, last name and phone number from the form and then autofill the widget when a checkbox is clicked stating that the user would like to receive mobile updates.
Below is what I've tried but it doesn't seem to be working. The code for the form is relatively long so I just included the relevant fields but here is link to the full form: http://support.ddfl.org/site/Donation2?df_id=9442&mfc_pref=T&9442.donation=form1
I'm very new to Javascript so I'm not entirely sure if this is possible. Just an fyi, I also included console statements so I could see if the values were working.
<input type="text" name="billing_first_namename" id="billing_first_namename"
<input type="text" name="billing_last_namename" id="billing_last_namename"
<input type="text" name="donor_phonename" id="donor_phonename"
<input type="checkbox" name="mcoptin" onclick="FillMobileCause(this.form)" value="this.form"> Opt in to receive mobile updates.
Mobile messaging powered by Mobilecause<script>!function(d,s){var s=d.createElement("script"),h=(document.head||d.getElementsByTagName('head')[0]);s.src="https://app.mobilecause.com/public/messaging_widgets/q71xd/source";h.appendChild(s);}(document);</script>
<script>
function FillMobileCause(f){
if(f.mcoptin.checked == true){
console.log(f.billing_first_namename.value);
console.log(f.billing_last_namename.value);
console.log(f.donor_phonename.value);
if(f.billing_first_namename.value.length>=1){
f.firstname.value = f.billing_first_namename.value;
}else {
f.firstname.value = '';
}
if(f.billing_last_namename.length>=1){
f.lastname.value = f.billing_last_namename.value;
}else{
f.lastname.value = '';
}
if(f.donor_phonename.length>=1){
f.mobilenumber.value = f.donor_phonename.value;
}else{
f.mobilenumber.value = '';
}
console.log(f.firstname.value);
}
}
</script>
Please let me know if I'm leaving off important details. This is also my first StackOverflow post. ;)
I appreciate your help!
Your main issue is that you were referring to inputs in the mobilecause form as if they were in the same form, but they are in another (nested in your f main form).
function FillMobileCause(f){
var mcF = f.getElementsByClassName('mc-triggersubscription')[0];
if(f.mcoptin.checked == true){
mcF.firstname.value = f.billing_first_namename.value;
mcF.lastname.value = f.billing_last_namename.value;
mcF.mobilenumber.value = f.donor_phonename.value;
}
}
f is still the main form (the one that is the parent of the checkbox).
But now we have another one, mcF (mobilecauseForm), which is selected using the getElementsByClassName (this will search for a child with the mc-triggersubscription class). The [0] part is so the first match is selected (getElementsByClassName returns an array.
After that, all we need to do is assign the f inputs' values to the mcF ones.
Note: I left behind the "if empty" validation for simplifying. Anyway I don't think it's really needed, if a value is empty, there is no major issue in just copying it to the mobilecause value.
So basically what I'm trying to do as a measure of security (and a learning process) is to my own "Capthca" system. What happens is I have twenty "label's" (only one shown below for brevity), each with an ID between 1 and 20. My javascript randomly picks one of these ID's and makes that picture show up as the security code. Each label has its own value which corresponds to the text of the captcha image.
Also, I have the submit button initially disabled.
What I need help with is figuring out how to enable the submit button once someone types in the proper value that matches the value listed in the HTML label element.
I've posted the user input value and the ID's value and even when they match the javascript won't enable the submit button.
I feel like this is a really really simple addition/fix. Help would be much much appreciated!!!
HTML code
<div class="security">
<label class="captcha enabled" id="1" value="324n48nv"><img src="images/security/1.png"></label>
</div>
<div id="contact-div-captcha-input" class="contact-div" >
<input class="field" name="human" placeholder="Decrypt the image text here">
</div>
<input id="submit" type="submit" name="submit" value="Send the form" disabled>
Javascript code
//Picks random image
function pictureSelector() {
var number = (Math.round(Math.random() * 20));
//Prevents zero from being randomly selected which would return an error
if (number === 0) {
number = 1;
};
console.log(number);
//Set the ID variable to select which image gets enabled
pictureID = ("#" + number);
//If the siblings have a class of enabled, remove it
$(pictureID).siblings().removeClass("enabled");
//Add the disabled class to all of the sibling elements so that just the selected ID image is showing
$(pictureID).siblings().addClass("disabled");
//Remove the disabled class from the selected ID
$(pictureID).removeClass("disabled");
//Add the enabled class to the selected ID
$(pictureID).addClass("enabled");
};
//Calls the pictureSelector function
pictureSelector();
//Gets the value of the picture value
var pictureValue = $(pictureID).attr("value");
console.log(pictureValue);
//Gets the value of the security input box as the user presses the keys and stores it as the variable inputValue
$("#contact-div-captcha-input input").keyup(function(){
var inputValue = $("#contact-div-captcha-input input").val();
console.log(inputValue);
});
console.log($("#contact-div-captcha-input input").val());
//Checks to see if the two values match
function equalCheck() {
//If they match, remove the disabled attribute from the submit button
if ($(pictureValue) == $("#contact-div-captcha-input input").val()) {
$("#submit").removeAttr("disabled");
}
};
equalCheck();
UPDATE
Fiddle here
UPDATE #2
$("#contact-div-captcha-input input").keyup(function(){
var inputValue = $("#contact-div-captcha-input input").val();
console.log(inputValue);
if (pictureValue === inputValue) {
$("#inputsubmit").removeAttr("disabled");
}
});
So I got it working 99.9%, now the only problem is that if someone were to backspace or delete the correct value they have inputted, the submit button does not then change back to disabled. Any pointers?
Known issue.
Give your button a name OTHER THAN submit. That name interferes with the form's submit.
EDIT
A link was requested for this -- I don't have a link for pure JavaScript, but the jQuery docs do mention this issue:
http://api.jquery.com/submit/
Forms and their child elements should not use input names or ids that
conflict with properties of a form, such as submit, length, or method.
Name conflicts can cause confusing failures. For a complete list of
rules and to check your markup for these problems, see DOMLint.
EDIT 2
http://jsfiddle.net/m55asd0v/
You had the CSS and JavaScript sections reversed. That code never ran in JSFiddle.
You never re-called equalCheck. I added a call to your keyUp handler.
For some reason you wrapped pictureValue inside a jQuery object as $(pictureValue) which couldn't have possibly done what you wanted.
Basic debugging 101:
A console.log inside of your equalCheck would have shown you that function was only called once.
A console log checking the values you were comparing would have shown
that you had the wrong value.
Basic attention to the weird highlighting inside of JSFiddle would have shown you had the code sections in the wrong categories.
I have a website with a form. The form is filled by user with data for example i show to user:
<input type='text' value="" name="dsa" />
And he fills it with value of "3";
And he clicks button "save". Now i want to have the whole HTML of the website including values of fields. So i use:
document.documentElement.innerHTML
But i get:
<input type='text' value="" name="dsa" />
But i want to get this:
<input type='text' value="3" name="dsa" />
NOTICE I want to take the whole HTML of the website, not only one field. I dont know what fields will be on the website so i need a general solution.
AFAIK you can't get this from the HTML code, as the HTML code does not change when the user inputs something in a Input text field.
What you could do is get all input fields on the page and get their values with something like this:
var inputs, index;
inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
// deal with inputs[index] element.
}
The code is from this post: https://stackoverflow.com/a/2214077/312312
I was too lazy to write it down my self :P
In jQuery I do
$(function() {
$('input').keyup(function() {
$(this).attr('value', $(this).val());
});
});
Because the value attribute isn't set after key up
You could try to set a live event on a whole document that will set attribustes to html with values user set in or set them on your submit.
First way for example
$("body").on("change", "select,input,textarea", function(){
$(this).attr("value", $(this).val());
});
But this should not be done so blindly, and you'll get problems with reset. And you should solve problem with selected radio, checkbox and other attributes, not only values.
Second way is to serialize whole page when it really needed.
var serialize = function(el){
$("select, input, textarea").each(function(){
$(this).attr("value", $(this).val()); //the same way as upper
});
}
$(".serialize").click(function(){
var inner = $("body"),
html;
serialize(inner);
html = inner.html(); //here you will get whole html with setted attributes
});
This way seems to be better because there wont be delegation of unnecessary event.
http://jsfiddle.net/CeAXL/2/ - test example.
But in both ways it's not good idea to set permanent values to DOM itself.