I have a form for editing a ticket that requires a "Reason for Edit". What I would like to do is have that automatically filled in as a result of when any of the input fields or the select dropdown changes. I know this can be done with javascript and an onChange event and have it modify (I believe) the innerHTML of the textarea. I'm strong on PHP/MySQL but javascript is definitely my weakness.
What I do not know and have been unsuccessful searching for, is exactly how to code this. As an example of what I have would be the following code:
<!-- Customers name -->
<input type='text' name='customer_name' onChange="updateReason('Updated Customer Name')" /><br><br>
<!-- Customer Email -->
<input type='text' name='customer_email' onChange="updateReason('Updated Customer Email')" />
If either of those two would be changed then the contents of a textarea would be updated and end with a carriage return.
Any help (or even pushed in the right direction / links to a guide) is appreciated.
HTML:
<form name="frmTest" action="test.html">
<textarea name="reason"></textarea>
<!-- Customers name -->
<input type='text' name='customer_name' onChange="updateReason('Updated Customer Name')" />
<!-- Customer Email -->
<input type='text' name='customer_email' onChange="updateReason('Updated Customer Email')" />
</form>
native HTML implementation:
function updateReason(text) {
document.frmTest.reason.value += text + '\r\n';
}
My implementation separates the business logic from the design. It also uses more advanced features of JavaScript (which are supported by practically every browser).
http://jsfiddle.net/xrZk2/1/
For the lazy, create a textarea like so:
<input type="text" name="customer_name" id="customer_name" /><br /><br />
<input type="text" name="customer_email" id="customer_email" /><br /><br />
<textarea name="customer_change_log" id="customer_change_log" readonly="readonly"></textarea>
And use the following JavaScript.
(function () {
'use strict';
var updateReason = function (reason) {
document.getElementById('customer_change_log').innerHTML += reason + '\n';
};
document.getElementById('customer_name').onchange = function () {
updateReason('Updated Customer Name');
};
document.getElementById('customer_email').onchange = function () {
updateReason('Updated Customer Email');
};
}());
And a little CSS never hurt anyone.
#customer_change_log {
height: 5em;
resize: vertical;
width: 15em;
}
A somewhat different approach:
HTML:
<p><label>Customer Name: <input type='text' name='customer_name'/></label></p>
<p><label>Customer Email: <input type='text' name='customer_email'/></label></p>
<p><label>Edit Reason: <textarea id="edit_reason" rows="6" cols="60"></textarea></label></p>
JS:
(function() {
var reasons = {
'customer_name': 'Updated Customer Name',
'customer_email': 'Updated Customer Email'
};
var inputs = document.getElementsByTagName("INPUT"), len, i, input;
var editReason = document.getElementById("edit_reason"), reasonText;
for (i = 0, len = inputs.length; i < len; i++) {
input = inputs[i];
input.onchange = (function(name) {
return function() {
reasonText = editReason.value || "";
if (reasons[name]) {
if (reasonText.indexOf(reasons[name]) < 0) {
editReason.value = reasonText + '\n' + reasons[name];
editReason.value = editReason.value.replace(/^\n+/, '');
}
}
};
}(input.name));
};
}());
You can see it in this fiddle. The biggest difference is in the separation of the logic from the markup, using this:
var reasons = {
'customer_name': 'Updated Customer Name',
'customer_email': 'Updated Customer Email'
};
The input tag that needs to be updated give it id or a class, each tag has unique id so its better to give it id like this
<input type='text' id="id-name" />
You need to add jQuery file and attach jQuery file with your html page. Attachment is written in head tag and is shown as follows.
<head>
<script src="jquery.min.js"></script>
</head>
On the following input tag wen values is changes the function updateReason is called. Code in the script tag is written in the same html file and if you want to separate your JavaScript or jQuery code from html you can write that in .js file without the script tag and just attach that file in your html page.
<input type='text' name='customer_name' onChange="updateReason('Updated Customer Name')" />
<script>
function updateReason(text)
{
// # is used for id and . is used for referring class in jQuery
$('#id-name').val(text);
}
</script>
Related
Ok so I am running into a really weird bug on my Wordpress site that hope is just my ignorance because this just seems too weird.
So I am working with styling a couple of input tags as well as a ReCaptcha form. I found some documentation at https://developers.google.com/recaptcha/old/docs/customization that I have been following. Basically what I want is the clean theme listed at that link and to do some showing/hiding of the captcha based on certain events.
I do realize that the top of the article mentions this version of the api is old, but the plugin I am using has some recaptcha code entangled in their code, so I figured I would try this first instead of making major modifications to the plugin.
So here is the code I am using
<!-- Code added by me-->
<script type="text/javascript">
var RecaptchaOptions = {
theme : 'clean'
};
function toggleCaptcha(inputField)
{
alert('working');
}
</script>
<!-- End code added by me -->
<script>
function validateGoodNewsUser(frm, requireName) {
requireName = requireName || false;
if(requireName && frm.goodnews_name.value=="") {
alert("Please provide name");
frm.goodnews_name.focus();
return false;
}
if(frm.email.value=="" || frm.email.value.indexOf("#")<1 || frm.email.value.indexOf(".")<1) {
alert("Please provide a valid email address");
frm.email.focus();
return false;
}
// check custom fields
var req_cnt = frm.elements["required_fields[]"].length; // there's always at least 1
if(req_cnt > 1) {
for(i = 0; i<req_cnt; i++) {
var fieldName = frm.elements["required_fields[]"][i].value;
if(fieldName !='') {
var isFilled = false;
// ignore radios
if(frm.elements[fieldName].type == 'radio') continue;
// checkbox
if(frm.elements[fieldName].type == 'checkbox' && !frm.elements[fieldName].checked) {
alert("This field is required");
frm.elements[fieldName].focus();
return false;
}
// all other fields
if(frm.elements[fieldName].value=="") {
alert("This field is required");
frm.elements[fieldName].focus();
return false;
}
}
}
}
return true;
}
</script>
<form method="post" class="goodnews-front-form" onsubmit="return validateGoodNewsUser(this,false);">
<div><label>Your Name:</label> <input type="text" name="goodnews_name"></div>
<div><label>*Your Email:</label> <input type="text" name="email" onfocus="toggleCaptcha(this)"></div>
<p><script type="text/javascript" src="<!--Captcha api url here-->"></script>
<noscript>
<iframe src="<!--Captcha api url here-->" height="300" width="500" frameborder="0"></iframe><br/>
<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
</noscript></p>
<div><br>
<input type="submit" value="Subscribe">
</div>
<input type="hidden" name="goodnews_subscribe" value="1">
<input type="hidden" name="list_id" value="1">
<input type="hidden" name="required_fields[]" value="">
</form>
So the problem I am running into is when I load the page, I see the clean theme for ReCaptcha and the alert shows up when I click inside the input box for the email. But if I change my added code by adding a single space like this
<!-- Code added by me-->
<script type="text/javascript">
var RecaptchaOptions = {
theme : 'clean'
};
<<<<<<<< Single new line space added.
function toggleCaptcha(inputField)
{
alert('working');
}
</script>
The whole thing breaks and the page loads with the standard red ReCaptcha and my functions don't get called.
I don't mind not using spaces, but that seems very odd that a space would make the difference. Am I missing something here? Is this caused by the outdated api?
Edit:
I was asked to try to get a jsfiddle working (or not working???). I stripped out everything except the form and the function call. Even the ReCaptcha was taken out and I still can not get it to call the function. This may be my lack of knowledge on jsfiddle or it may get closer to the real problem. https://jsfiddle.net/b257779t/
I have a 'users page'. I would like to give a textbox for entering the no. of users. On click of submit 'n' no of user forms need to be presented to user.
User1
first name -
last name -
User2
first name -
last name -
.
.
.
UserN
first name -
last name -
I don't know the value of 'N' upfront. So it won't be a good idea to write multiple 'divs' in my html.
Requirement:Rather I want to have a user template div. And copy the template 'n' times depending on the value of 'n' in the textbox. But I would also want all the 'divs' to have different ids like 'user1', 'user2' etc.
I cannot figure out a way to do this apart from populating my html with too many 'divs'. Would need help achiving the Requirement specified.
Looking for a template like:-
<div id="user-template" class="hidden">
<label class="lbl"><b>Handle:</b></label><input type="text" id="first_name" value=""/>
</div>
And wanted to have id="user-template" change for all new divs.
You can try something like this:
You can make a template and append it to the DOM for the number entered in the input field.
$(document).ready(function() {
$("#createForms").click(function() {
var numOfForms = $("#numOfForms").val();
var template = $('#hidden-template').html();
for (var i = 0; i < numOfForms; i++) {
$('#targetDiv').append("<p>User" + (i + 1) + ":</p>");
$('#targetDiv').append(template);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="numOfForms"></input>
<input type="button" id="createForms" value="Get Fields"></input>
<div id="targetDiv"></div>
<script id="hidden-template" type="text/x-custom-template">
<div id="user-template" class="hidden">
<p>First Name:
<input type="text" name="firstName"></input>
</p>
<p>Last Name:
<input type="text" name="lastName"></input>
</p>
<br>
</div>
</script>
A simple way is to write a function that takes the n value and returns the actual dom that you can append to some parent element on your page. A simple example below:
function createNDivs(n) {
if(!n) return;
var fragment =document.createDocumentFragment();
for(var i=0;i<n;i++) {
var div = document.createElement('div');
fragment.appendChild(div);
}
return fragment;
}
My Goal was to redirect a user after filling out a Google form on Wordpress. I have managed to do this and restyle the form with css. I have used the following tutorial: how-to-style-google-forms-and-redirect-it-to-your-desired-thankyou-page
The problem is that I can not get my custom javascript validation to work in Wordpress. I have tested the code locally and replicated it on JSFiddle.
<body>
<h1 id="heading">This Is Kip's Form Test</h1>
<form action="http://www.wikipedia.org" method="GET" onsubmit="return(validate());">
<ul id="special-list">
<li>First name:<input type="text" name="entry.198534167" value=""></li>
<li>Last name:<input type="text" name=","entry.641095175" value=""></li>
<li><input type="radio" name="sex" value="male" checked>Male</li>
<li><input type="radio" name="sex" value="female">Female</li>
</ul>
<input type="submit" value="Submit">
</form>
</body>
Javascript:
var errors = [];
function validate(){
var check_name = /^[a-zA-Z ]{2,30}$/;
var elements = ["entry.198534167","entry.641095175"];
var first_name = document.forms[0].elements[0].value;
var last_name = document.forms[0].elements[1].value;
if(!check_name.test(first_name)){
errors[errors.length] = "Your first name was not entered correctly. Use letters A - Z.";
document.forms[0].elements[0].focus() ;
}
if(!check_name.test(last_name)){
errors[errors.length] = "Your last name was not entered correctly. Use letters A - Z.";
}
if (errors.length > 0) {
reportErrors(errors);
return false;
}
return true;
}
function reportErrors(errors){
var msg = "Please Enter Valid Data...\n";
for (var i = 0; i<errors.length; i++) {
numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}
I have tried linking the my javascript file in the head, enqueue in my child theme functions.php file, and lastly in the body of the page template file.
Lastly, I know that that my javascript page is being added because it shows up in the developer tools resources listing. I have also tried an alert message that works when the document is ready. However, the validation still does not work.
After running my javascript through jslint and making sure that there were no fatal flaws, I found my error in the html form. The code I provide in the jsfiddle worked because the function validate() was supplied in the form attribute onsubmit="".
On WordPress in the html I had onsubmit="submitted=true;". I believe this was the code copied from the Google Form. My fiddle had the correct html (I did not need the ;) and the WordPress code I had was incorrect.
Please excuse my inexperience as I am not a programmer just someone who dabbles at trying to make something work. I'm not sure of the correct terminology and complicated explanations will go straight over my head!
In essence I am trying to get part of the URL of a web page passed to a simple Form that is linked to a shopping cart. i.e. how do I get the filename into the form where I have xxxxxxx. Is it possible in Javascript?
<script type="text/javascript">
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
document.write (filename);
</script>
<form action="http://www.mywebspace.com/cf/add.cfm" method="post">
<input type="hidden" name="userid" value="12345678">
<input type="hidden" name="product" value="xxxxxxx">
<input type="hidden" name="price" value="5.00">
<input type="Submit" value="Buy now!">
</form>
I've provided a snippet code that will work with your current HTML structure. Though I do suggest you give the product field an id to prevent the necessity to loop and search elements:
var url = window.location.pathname,
filename = url.substring(url.lastIndexOf('/')+1);
fields = document.getElementsByTagName('input');
for(var i = 0; i < fields.length; i++){
if(fields[i].name == 'product') {
fields[i].value = filename;
break;
}
}
If the form only exists once on a given page, this is an easy solution:
Change it to be:
<input type="hidden" id="productField" name="product" value="xxxxxxx">
In your javascript,
document.getElementById('productField').value = filename;
Yes this is possible.
Instead of doing document.write you need to update the form. Assuming your filename value is currently correct:
//js
document.getElementById( "name-of-file").value = filename;
<!- html -->
...
...
I have this text box here...
<input name="search" type="text" maxlength="512" id="search" class="searchField" autocomplete="off" title="" />
and I also have this submit
<input type="submit" name="btnSearch" value="Search" onclick="location.href='http://www.website.com/search/';" id="btnSearch" class="buttonSearch" />
what I am trying to do is add whatever is in the text box in my
onclick="location.href='http://www.website.com/search/';"
so it would look like this..
onclick="location.href='http://www.website.com/search/what ever the user searches';"
how would I go about doing this, I have been googling my little heart out.
Please avoid mixing JavaScript and HTML. You can remove onclick attribute and replace it with this in plain JavaScript somewhere after the DOM has loaded:
document.getElementById('btnSearch').onclick = function() {
var search = document.getElementById('search').value;
var searchEncoded = encodeURIComponent(search);
window.location.url = "http://www.website.com/search/" + searchEncoded;
}
Also remember about escaping the search box, e.g. using encodeURIComponent(). Here is a working jsfiddle example.
This should work:
onclick="location.href='http://www.website.com/search/'+document.getElementById('search').value;"
But I wouldn't ever write that in one of my project as writing script directly on tags is a bad practice.
Here is a working jsfiddle
I moved the event handler out of the button as it is more maintainable. Also I encode the search query so that it gets to the server properly.
var search = document.getElementById('search');
var submit = document.getElementById('btnSearch');
submit.addEventListener('click', function(e) {
var searchValue = encodeURIComponent(search.value); // encode the search query
window.location.href = 'http://www.website.com/search/' + searchValue ;
});
You can add it to the onclick event like so
document.getEelementById("btnSearch").onclick = function(){
location.href='http://www.website.com/search/' + document.getEelementById("search").value;
}
edit: aaaaand too slow... oh well. At least this is not inline.
You would be better off using the < script> tag for this task. Example:
<input name="search" type="text" maxlength="512" id="search" class="searchField" autocomplete="off" title="" />
...
<input type="submit" name="btnSearch" value="Search" id="btnSearch" class="buttonSearch" />
<script type="text/javascript">
var button= document.getElementById('btnSearch');
button.onclick= function(){
var text= document.getElementById('search').value;
location.href='http://www.website.com/search/'+text;
}
</script>
However, you should try to 'clean' a little the text from the textbox so when you append it to the url you get a valid url. You should trim the text, then search for special characters and escape them, etc.