How do I autofill a widget with form inputs using Javascript? - javascript

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.

Related

Preventing users from changing form values of a form using "inspect" in his web browser?

I am building an application based on node.js and using handlebars as view engine. the problem is I have a form that when submitted it inserts data into the database. this forms passes some values that the user does not see, like the bookingAmount for example. I currently use a hidden input field that contains the value for the booking which is passed to nodeJs through req.body. the problem is the user can open the "inspect element" in his browser and change this booking Amount before submiting the form !! how can I prevent such thing from happening ?
code for the handlebars form (inside page bookingDetails.handlebars):
<form action="/finish" method="POST" style="display: inline;">
<input type="hidden" name="bookingId" value="{{data.bookingId}}">
<input type="hidden" name="Id" value="{{data.user.userId}}">
<input type="hidden" name="bookingAmount" value="{{data.bookingAmount}}">
<button type="submit" id="finish">Finish Tour</button>
</form>
the above data.XXXXX is passed on from nodeJs when the page loads by the below code:
var bookingDetails=bookings.findOne({where:{bookingId: req.body.bookingId}, include: [{model: locations},{model: user}).then((bookingDetails)=>{
res.render('tPages/bookingDetails',{data: bookingDetails})
})
The same problem exists for some buttons on the page. the page contains buttons like edit , cancel and submit. I want to make those buttons enabled or disabled depending on the booking status. I am using a script in the handlebars page to change the disabled property to true or false depending on the booking status. still the user can change the "disabled" property in his browser and use the button, here is the script I use:
<script>
status='{{data.bookingStatus}}'
if (status=='accepted'){
document.getElementById("cancel").disabled = true;
}else if (status=='pending'){
document.getElementById("finish").disabled = true;
document.getElementById("noshow").disabled = true;
}else if (status=='finished' || status =='noshow' || status=='cancelled' || status=='rejected'){
document.getElementById("cancel").disabled = true;
document.getElementById("finish").disabled = true;
document.getElementById("noshow").disabled = true;
}
</script>
what is the solution for such issues ?
Do Not Rely on user input
Even if you try hacks to disable the right click menu etc. these are easily cirumvented (I can just post the form information directly using cURL or similar).
Validate on the server ALWAYS.
If some items need to be disabled, make sure the same logic applies on the server and reject information that does not follow your business rules.
Also don't disable the context menu or try and prevent the browser doing things it is designed to do, this will only lead to other issues, frustrates users and provides you with little / no protection at all.

How to set a input text (with no ID or name) value with a subsequent submit of that input text?

I have been trying already all kind of code snippets in Chrome Dev tools on this website:
http://kiwisdr.sk3w.se:8073/?#
This is a software defined radio running on a webserver.
I would like to use Javascript to set the frequency (and submit) so that I can change the frequency the receiver is currently tuned to.
Manually on the GUI the user can just type a frequency (with or without enter) and the new frequeny inside the input box will be tuned.
This is the HTLM part of the website containing the input (no ID or name, so I am not sure how to properly adress this):
<form id="id-freq-form" name="form_freq" action="#" onsubmit="freqset_complete(0); return false;">
<input class="id-freq-input w3-input w3-border w3-hover-shadow" style="padding:0 4px;max-width:74px" size="8" onkeydown="freq_keydown(event)" onkeyup="freqset_keyup(this, event)" type="text" value="" onchange="w3_input_change('undefined', 'undefined')">
</form>
I managed to set the frequency, but I am stuck on how to make it submit.
This is the code I used to set the frequency input box to a certain value (1234.50):
targetForm = document.forms['form_freq'];
targetForm.elements[0].value = '1234.50';
I already tried to trigger the keydown, keyup or change events using some snippets I found, but I am not sure I adress the right elements in the form with it.
All I want to do is to mimic a user entry by code :-)
Could someone point me into the right direction by having a look on the way how the input works on this website and how I can make the website update the currently received frequency with javascript?
Thanks.
Short answer:
freqset_keyup(document.forms[1][0], null)
Nicer answer:
function change_freq(new_freq) {
var form = document.forms['form_freq'];
var freq_input = form.elements[0];
freq_input.value = new_freq;
freqset_keyup(freq_input, null);
}
change_freq(1234.50)

Homemade "Captcha" System - One minor glitch in javascript, can't enable submit button

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.

dynamic javascript when using load->view

I have a form with a « newInput » button, which add dynamically in javascript a new input when I click to it.
When I have an error in my form, I re-load the view with the form. It’s normal, but .. Because I use dynamic javascript for adding new input, all the input added are removed when I reload..
There is something I can do ?
This is an exemple of my view.tpl :
<input
type="text"
placeholder="ex: cerise"
onfocus="javascript:autoComplet('jigd1', '{site_url('recettes/getIngredient')}')"
value="{set_value('igd[]')}" id="jigd1" name="igd[]"
/>
{form_error('igd[]')}
I add a partiel code of my js file
var cpt=1;
function addField(uriIngredient, uriLabel) {
try
{
cpt=cpt+1;
var inputIgd = document.createElement('input'),
button = document.createElement('input'),
div = document.createElement('div'),
inputIgd.setAttribute('type','text');
inputIgd.setAttribute('name','igd[]');
inputIgd.setAttribute('id','jigd'+cpt);
button.setAttribute('type','button');
button.setAttribute('onclick','javascript:supField("igd'+cpt+'")');
button.setAttribute('value','Supprimer');
div.setAttribute('id','igd'+cpt);
div.appendChild(inputIgd);
div.appendChild(button);
document.getElementById("listIgd").appendChild(div);
...
After some research, I tried to look at what someone said me, that's say localStorage, and it is very nice. But I used an exemple for only one input because i wrote it in my html, but I don't know how to do for recreate all inputs .. And particularly because I use javascript to add new inputs, I don't know if I can recreate all inputs .
check the form before submitting, that way you won't have to reload the page, for example using jquery ...
$("#myformid").on("submit", function(){
var goodtogo = true;
// some code here to check the form, if there's an error --> goodtogo = false;
if (!goodtogo) return false; // and some other code to display the errors
});
That way, if there's an error , the form won't submit and won't reload.
If you have to check something in a database (for example) like checking if a username already exists, you'll have to use ajax.

cakephp - Javascript

We are working on an application using the CakePHP framework
Basically, its a questionnaire application and it has a few dependant questions, i.e. based on a response to a specific question, it needs to show or hide the next one
For e.g.
Question: Are you married? Yes/No
If the user selects Yes, then using javascript the next question gets displayed for user input
Question: Spouse's name
Saving this information is fine, but when editing, when populating the form, we would want to be able to display the fields for which user has inputted data - in this case, it needs to show the field that has the spouse's name
Since by default we are hiding the spouse name field, when editing, it doesn’t display the field, even though there is a value to it
Is there some way that CakePHP can handle this or does it require us to write some javascript to take care of this?
Thanks in advance.
CakePHP does not manage this for you. While CakePHP is very powerful and a great framework, it will not write this kind of logic for you. You must write it.
I would suggest making the EDIT screen different from the ADD screen. Build the list of values from the database and display the fields that have values (and include any empty fields that should require values).
Keep in mind reusable does not necessarily mean that all CRUD actions fit into the same view.
Like others I advise you use differents EDIT and ADD screens.
But you can try make it with Javascript like this:
<script>
function enableDisableField(targetFieldId){
var targetField = document.getElementById(targetFieldId);
var checkbox = event.target;
console.log(checkbox.checked);
if (checkbox.checked){
targetField.disabled = false;
targetField.value = "empyt";
}else{
targetField.disabled = true;
targetField.value = "empyt";
}
}
</script>
<label><input type="checkbox" onchange="enableDisableField('married')"/> Merried</label>
<?= $this->Form->input('married',['label' => false, 'disabled']); ?>
It works well for ADD, but if you and EDIT you have to change de disable value according a field value:
<label><input type="checkbox" onchange="enableDisableField('married')"/> Merried</label>
<?= $this->Form->input('married',['label' => false, !isset($user->married) ? 'disabled' : '' ]); ?>

Categories

Resources