How do I convert some ugly inline JavaScript into a function? - javascript

I've got a form with various inputs that by default have no value. When a user changes one or more of the inputs all values including the blank ones are used in the URL GET string when submitted.
So to clean it up I've got some JavaScript that removes the inputs before submission. It works well enough but I was wondering how to put this in a js function or tidy it up. Seems a bit messy to have it all clumped in to an onclick. Plus I'm going to be adding more so there will be quite a few.
Here's the relevant code. There are 3 separate lines for 3 separate inputs. The first part of the line has a value that refers to the inputs ID ("mf","cf","bf","pf") and the second part of the line refers to the parent div ("dmf","dcf", etc).
The first part is an example of the input structure:
echo "<div id='dmf'><select id='mf' name='mFilter'>";
This part is the submit and js:
echo "<input type='submit' value='Apply' onclick='javascript: if (document.getElementById(\"mf\").value==\"\") { document.getElementById(\"dmf\").innerHTML=\"\"; }
if (document.getElementById(\"cf\").value==\"\") { document.getElementById(\"dcf\").innerHTML=\"\"; }
if (document.getElementById(\"bf\").value==\"\") { document.getElementById(\"dbf\").innerHTML=\"\"; }
if (document.getElementById(\"pf\").value==\"\") { document.getElementById(\"dpf\").innerHTML=\"\"; }
' />";
I have pretty much zero JavaScript knowledge so help turning this in to a neater function or similar would be much appreciated.

your script block in your HEAD:
<script type="text/javascript">
function yourFunctionName(){
...your javascript goes here...
}
</script>
and then your onclick:
onclick="javascript:yourFunctionName()"

Seems pretty simple:
<script>
function doSubmit() {
if (document.getElementById("mf").value == "")
document.getElementById("dmf").innerHTML = "";
if (document.getElementById("cf").value == "")
document.getElementById("dcf").innerHTML = "";
if (document.getElementById("bf").value == "")
document.getElementById("dbf").innerHTML = "";
if (document.getElementById("pf").value == "")
document.getElementById("dpf").innerHTML = "";
}
</script>
<input type="submit" value="Apply" onclick="doSubmit();" />
Or you could even get fancy and do something like this:
<script>
function doSubmit() {
var inputs = {
"mf": "dmf",
"cf": "dcf",
"bf": "dbf",
"pf": "dpf"
};
for (var input in inputs) {
if (document.getElementById(input).value == "")
document.getElementById(inputs[input]).innerHTML = "";
}
}
</script>

if you were to use jquery (and there is no reason not to):
if your submit button had an id of say id="submit-button" this 'should' work and would handle any additional inputs that get added
$(document).ready(function () {
$("#submit-button").click(function () {
$(this).parents("form").find(':input').each(function() {
if ($(this).val() === "") {
$(this).innerHTML = "";
}
});
});
});
NOTE: I did not test above code at all
here is an updated version
$(document).ready(function () {
$("form").submit(function () {
$(this).find(':input').each(function() {
if ($(this).val() === "" && $(this).attr("type") !== "submit") {
$(this).attr('disabled', 'disabled');
}
});
});
});
this one is setting the blank inputs to disabled - I could not get the innerHTML = "" to work on Firefox 3.6 on Mac and I did not test above code on other browsers or OS
you would need to download jquery http://docs.jquery.com/Downloading_jQuery#Current_Release and include a reference to it in your html head
to use the innerHTML trick on the inputs parent span tag change the line $(this).attr('disabled', 'disabled'); to
if ($(this).parent().get(0).tagName === "SPAN") {
$(this).parent().get(0).innerHTML = "";
}

Related

javascript validating the whole form

Friends i am new to javascript, I am trying to write a script to validate the entire form whenever any input field value is changed of input fiels with the data attribute of required.
HTML
<form>
<input type="text" name="FirstName" class="inputField" data-required="true"></input>
<input type="text" name="MiddleName" class="inputField"></input>
<input type="text" name="LastName" class="inputField" data-required="true"></input>
</form>
SCRIPT
var field, required, isValid, fieldVal;
function validatedForm() {
field = document.querySelectorAll('.inputField');
document.getElementById("submitButton").disabled = true;
var isValid = true;
for(var i=0; i < field.length; i++){
required = field[i].dataset.required;
if(required){
field[i].addEventListener('blur', function(e){
fieldVal = this.value;
if(fieldVal == ''){
isValid = false;
}
checkSubmitBtn();
}, true);
}
}
function checkSubmitBtn() {
if(isValid = true) {
console.log(isValid);
document.getElementById("submitButton").disabled = false;
}
}
}
window.addEventListener("load", validatedForm);
PROBLEM 1:
The isValid is not updating hence even an empty blur on the input field makes the button disable to be false.
PROBLEM 2:
In case there are multiple forms on the page then how to validate only the desired forms .. just like in jQuery we add a script tag in the end to initialize the script according to it.
PROBLEM 3:
Is there a way to change the disable state of the button without the GetElementID ... I mean if that can be managed depending on the submit button of that particular form on the page where the script is suppose to work.
Any help will be highly appreciated. Thanks in advance.
I think you need something like the following form validation..
<script type="text/javascript">
var field, fieldVal, required = false;
function validatedForm() {
field = document.querySelectorAll('.inputField');
document.getElementById("submitButton").disabled = true;
field.forEach(function(elem) {
required = elem.dataset.required;
if(required){
elem.addEventListener('blur', function(e) {
checkSubmitBtn(field);
});
}
});
}
function checkSubmitBtn(field) {
var isDisabled = false;
field.forEach(function(elem) {
fieldVal = elem.value.trim();
if(fieldVal == ''){
isDisabled = true;
return false;
}
});
document.getElementById("submitButton").disabled = isDisabled;
}
window.addEventListener("load", validatedForm);
</script>
I hope it helps...
There are quite a few things going on here. First, your checkSubmitBtn function used a single = operator in the if statement. This won't actually check the variable, it instead will set the variable to that value. Here is the fixed function:
function checkSubmitBtn() {
if (isValid == true) {
document.getElementById("submitButton").disabled = false;
}
}
You mentioned not wanting to use getElementById. There are a few ways around this. One way would be to call the function once and store it in a variable to use later, like so:
var button = document.getElementById("submitButton");
...
function checkSubmitBtn() {
button.disabled = !isValid;
}
Another way would be to use jQuery. It still is technically calling getElementById in the backend, but the code is much simpler. If you wanted to avoid that, you also can still combine this with the technique I described above.
$("#submitButton").attr("disabled", !isValid);
I'd also like to point out that your code doesn't account for a situation where a form goes from invalid (starting point) to valid and back to invalid again. Say a user types in all of the fields but then backspaces everything. Your code will fall apart.
Lastly, your <input> HTML tags should not be closed. There are certain tags that are considered "self-closing", i.e. you don't have to write the closing tag, </input>.

if this input has value doesn't work in IE 9

I am using this simple code to filter through a search form with many text inputs and see if they have a value and then add a class.
Works perfectly in Chrome, safari and Firefox but not in IE9.
$('input[type="text"]').filter(function() {
if ($(this).val() !== '') {
$(this).addClass('used');
}
});
Please advice, thanks in advance!
EDIT
Change to each but doesn't solve the issue... Here it is with the event that triggers the function...
$(document).on('event-ajax-form-is-loaded', function() {
$('input[type="text"]').each(function() {
if ($(this).val() !== '') {
$(this).addClass('used');
}
});
});
From the limited information you shared, this is how you should be doing this:
$('input[type="text"]').filter(function() {
return $(this).val() !== '';
}).addClass('used');
.filter() is supposed to reduce a set of matched elements so its filter function should always return a bool instead of manipulating the DOM.
Edit: Based on your updated code snippet and the page link you shared in the comments, if you are using jQuery in WordPress, then its always safer to wrap the code like so:
(function($) {
/* jQuery Code using $ object */
})(jQuery);
enter code hereIn JS you can check the element value by getting their tag name
for (var i = 0; i < document.getElementsByTagName('input').length; i++){
if (document.getElementsByTagName('input')[i].value == "")
{
alert("The value of textbox at " + i + " is empty");
}
}
Working Demo
Or like what other people suggest, use a .each in JQuery
$('input[type="text"]').each(function(i){
if ($(this).val() == "") {
alert("The value of textbox at " + i + " is empty");
}
});
anohter Working Demo
If you insist to use filter and here you go
$('input[type="text"]').filter(function()
{ return $( this ).val() != ""; }).addClass("used");
Last Working Demo
and jquery filter reference

Place holder is not working

Place holder is not working in IE-9,so I used the below code for place holder.
jQuery(function () {
debugger;
jQuery.support.placeholder = false;
test = document.createElement('input');
if ('placeholder' in test) jQuery.support.placeholder = true;
});
// This adds placeholder support to browsers that wouldn't otherwise support it.
$(function () {
if (!$.support.placeholder) {
var active = document.activeElement;
$(':text').focus(function () {
if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
$(this).val('').removeClass('hasPlaceholder');
}
}).blur(function () {
if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
$(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
}
});
$(':text').blur();
$(active).focus();
$('form:eq(0)').submit(function () {
$(':text.hasPlaceholder').val('');
});
}
});
When I am taking the value of test,it shows null.How can I get the details of all input tag?
I think this will help you
if ($.browser.msie) {
$("input").each(function () {
if (IsNull($(this).val()) && $(this).attr("placeholder") != "") {
$(this).val($(this).attr("placeholder")).addClass('hasPlaceHolder');
$(this).keypress(function () {
if ($(this).hasClass('hasPlaceHolder')) $(this).val("").removeClass('hasPlaceHolder');
});
$(this).blur(function () {
if ($(this).val() == "") $(this).val($(this).attr("placeholder")).addClass('hasPlaceHolder');
});
}
});
}
I'm on my mobile so this is hard but really you need to do
JQuery.support.placeholder = typeof 'placeholder' in test !== 'undefined'
Because null means there isn't any placeholder value, but there is placeholder support
From what I understand you're saying that the placeholder in test is returning null
I suggest you don't write this yourself and go for an off-the-shelf solution. There's more complexity here that you'd probably want to tackle yourself if all you want is provide support for older browsers.
For example, here's the shim I'm using (and that is recommended on http://html5please.com): https://github.com/mathiasbynens/jquery-placeholder/blob/master/jquery.placeholder.js
Go ahead and read the code. These are some issues you need to have in mind when writing such shim:
detect the browser support,
keep track when the box contains the real input or not;
add a class to allow different text colour for the placeholder,
clear the placeholders before submitting the form,
clear the placeholders when reloading the page,
handle textarea,
handle input[type=password]
And that's probably not even all. (The library I've linked also hooks into jQuery in order to make .val() return '' when there's no real input in the box.
There's also another shim that uses a totally different approach: https://github.com/parndt/jquery-html5-placeholder-shim/blob/master/jquery.html5-placeholder-shim.js
This library doesn't touch the actual value of the input, but instead displays an element directly over it.
HTML:
<input type='text' id='your_field' value='Enter value'/>
jQuery:
$(document).ready(function(){
$("#your_field").on('focusout',function(){
if($("#your_field").val() == ''){
$("#your_field").val('Enter value');
}
});
$("#your_field").on('focus',function(){
if($("#your_field").val() == 'Enter value'){
$("#your_field").val('');
}
});
});
See DEMO
Also check when the form is posted because if the user submits the form without entering the field then Enter value will be posted as the value of the field.So do either validations in client side or check in the server side when submitting the form.

JQuery Validation results being placed outside of the cell

I'm having trouble getting the validation function results "Required field" to fill the text input box of a table.
The current code is placing the result to the right of the cell instead of inside.
I'm fairly positive it's the $(this).parent().append portion but after trying several other variations I haven't achieved the expected results.
*The code verifies that a value is currently in the cell by means of examining the class = requiredField attribute.
Any tips are much appreciated. -Thank you.
<script type="text/javascript">
$(document).ready(function() {
$('form#commentform').submit(function() {
$('form#commentform .error').remove();
var hasError = false;
$('.requiredField').each(function() {
if(jQuery.trim($(this).val()) == '') {
$(this).parent().append('<span class="error">*Required field</span>');
hasError = true;
}
});
if(!hasError) {
alert('Validation Complete');
}
return false;
});
});
</script>
You can use the after() method:
$(this).after('<span class="error">*Required field</span>');
http://api.jquery.com/after/

Onsubmit validate change background requried fields?

Anyone know of a good tutorial/method of using Javascript to, onSubmit, change the background color of all empty fields with class="required" ?
Something like this should do the trick, but it's difficult to know exactly what you're looking for without you posting more details:
document.getElementById("myForm").onsubmit = function() {
var fields = this.getElementsByClassName("required"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
if(!fields[i].value) {
fields[i].style.backgroundColor = "#ff0000";
sendForm = false;
}
else {
//Else block added due to comments about returning colour to normal
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
This attaches a listener to the onsubmit event of the form with id "myForm". It then gets all elements within that form with a class of "required" (note that getElementsByClassName is not supported in older versions of IE, so you may want to look into alternatives there), loops through that collection, checks the value of each, and changes the background colour if it finds any empty ones. If there are any empty ones, it prevents the form from being submitted.
Here's a working example.
Perhaps something like this:
$(document).ready(function () {
$('form').submit(function () {
$('input, textarea, select', this).foreach(function () {
if ($(this).val() == '') {
$(this).addClass('required');
}
});
});
});
I quickly became a fan of jQuery. The documentation is amazing.
http://docs.jquery.com/Downloading_jQuery
if You decide to give the library a try, then here is your code:
//on DOM ready event
$(document).ready(
// register a 'submit' event for your form
$("#formId").submit(function(event){
// clear the required fields if this is the second time the user is submitting the form
$('.required', this).removeClass("required");
// snag every field of type 'input'.
// filter them, keeping inputs with a '' value
// add the class 'required' to the blank inputs.
$('input', this).filter( function( index ){
var keepMe = false;
if(this.val() == ''){
keepMe = true;
}
return keepMe;
}).addClass("required");
if($(".required", this).length > 0){
event.preventDefault();
}
});
);

Categories