Problem showing table with Javascript condition - javascript

I have a Sprinv MVC Controller, when I submit a form I return the same page but with some objects and a String called hidden that has the value False. When I submit the form I have a window.onload function that gets the value of the this string and checks if it has the string value "false" to display 3 divs that were hidden but they didn't.
I'm struggling where is the problem because I tried a lot of things.
This is my HTML Form.
<form class="forms-sample" action="Buscar.do" method="POST" >
<div class="form-group">
<label>client:</label>
<input type="text" class="form-control" id="id" name="identificador" placeholder="DNI/NIF">
</div>
<button type="submit" class="btn btn-gradient-primary btn-gradient-aj mr-2">Obtenir Autoritzacions</button>
</form>
And here's the javascript code.
<script>
window.onload = function showTable() {
var z = ${hidden}
if(z.localeCompare("false") == 0){
var x = document.getElementById("Prueba");
var x2 = document.getElementById("Prueba2");
var x3 = document.getElementById("Prueba3");
x.style.display = "block";
x2.style.display = "block";
x3.style.display = "block";
}
}
</script>
I checked with innerHTML and the value Im getting is false so they localeCompare should do the If condition, I think the problem is in the if because i tried withouth the if and it works. Also I didnt post the divs Prueba/Prueba2/Prueba3 becasue they're not important, i mean they could be only a text.
SOLVED
I created a input type hidden with that the MVC controller returns and get it by javascript with z = document.getElementById('form1').elements[1].value . Thanks to #kemicofa for the tip.

I'm not familiar with Spring, but from the syntax in your js code, I'm assuming it replaces things with ${} with their Spring variables. I know with PHP or Handlebars, you need to provide the quotes yourself, so try replacing ${hidden} with "${hidden}".

The spring expression needs to be within single quotes;
var z = '${hidden}';

Related

javascript validation of the elements

I am running a code for my validatio where i am facing some issues
I have created a function to validate but based upon my html a little bit help is needed
Here it is:
My HTML code look alike
<div class="el-form-item">
<label for="streetAddress" class="el-form-item__label">Street Address</label>
<div class="el-form-item__content">
<div class="el-input">
<input type="text" autocomplete="off" class="el-input__inner validate">
</div>
</div>
</div>
here is the validation Function
function validate(){
var validateElements = document.getElementsByClassName("validate");
var inputs = Array.prototype.filter.call(validateElements,function(element){
return element.nodeName === 'INPUT';
});
for(var i=0; i < inputs.length; i ++ ){
var input = inputs[i];
if(input.value.length == 0){
// generic placeholder
input.placeholder = "kindly enter value";
// error class
input.classList.add("err");
// focus on the input [ optional ]
console.log(input.closest('.el-form-item__label'));
input.closest('.el-form-item__label').classList.add('err'); // error happening here
input.focus();
// break the loop [ optional ]
break;
}
}
}
two things i am trying to do here
i want to cover the label also to red which is defined in the .err class
and also want to place the error just underneath the input element instead of inside the placeholder.
i posted my code code above, please guide
i hope the making this validation function as mixin so i can use in my vueJS app, if anyone can guide with that, would be much much appreciated
i am trying to include inputs first and then plan to bring other form elements with this.

Get the value of an <input type="text"> that was created dynamically inside a modal

i would like to get the value of an <input type="text"> that was created dynamically inside a modal and put it into variable "newcomment".
This is how i make the input:
var newcomment;
var p = $("<p>");
p.append("Some text");
p.append("</p>");
p.append("<input type='text'id='comment_text' value='Comment'"+"onblur=newcomment=$('#comment_text').val()"+" onfocus=if(this.value==this.defaultValue)this.value=''>"+"</input>");
$("div.modal-body").append(p);
The problem is when i write something like "ok" inside the textbox in the modal, and after i focusout from the textbox: newcomment seems not update to "ok" and still have the default "Comment" value.
1st: You need to use newcomment=this.value instead of newcomment=$('#comment_text').val()
2nd: No need to add + signs in your input html code while you not trying to concatenate string by putting variables to it
var newcomment;
var p = $("<p>");
p.append("Some text");
p.append("</p>");
p.append("<input type='text' id='comment_text' value='Comment' onblur='newcomment=this.value; alert(newcomment);' onfocus=if(this.value==this.defaultValue)this.value='' />");
$("body").append(p);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Not really the answer here, but might help you get at the root of the problem.
JS:
var newComment, defaultValue;
function doOnBlur(){
newComment = $('#comment_text').val()
}
function doOnFocus(){
if($('#comment_text').val() == defaultValue){
$('#comment_text').val('')
}
}
HTML:
<input type='text' id='comment_text' placeholder='Comment' onblur='doOnBlur()' onfocus='doOnFocus()' />
<!-- inputs dont have a close tag, also should use placeholder for temporary text -->
from here, you can set breakpoints in the debugger and see where your code is going wrong. You can also modify the functions much more easily rather than writing the executing code in the HTML

How do you return data from javascript into a html form?

I was wondering if anyone can help? What I am trying to do is retrieve the word count from javascript code into a form and then pass it into php along with the rest of the form which will check that the word count is a certain length or else it won't be submitted.
The javascript is as follows.
counter = function() {
var value = $('#msg').val();
if (value.length == 0) {
$('#wordCount').html(0);
$('#totalChars').html(0);
$('#charCount').html(0);
$('#charCountNoSpace').html(0);
return;
}
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
var totalChars = value.length;
var charCount = value.trim().length;
var charCountNoSpace = value.replace(regex, '').length;
$('#wordCount').html(wordCount);
$('#totalChars').html(totalChars);
$('#charCount').html(charCount);
$('#charCountNoSpace').html(charCountNoSpace);
};
$(document).ready(function() {
$('#count').click(counter);
$('#msg').change(counter);
$('#msg').keydown(counter);
$('#msg').keypress(counter);
$('#msg').keyup(counter);
$('#msg').blur(counter);
$('#msg').focus(counter);
});
My problem is returning wordCount into a hidden field in a form. I am not too good with javascript and am not sure how to modify this code to make it work. The rest I can figure out but am stuck here. Thank you for your help, it is greatly appreciated.
$('#wordCount').val(wordCount);
$('#totalChars').val(totalChars);
$('#charCount').val(charCount);
$('#charCountNoSpace').val(charCountNoSpace);
Use .val() instead of .html(), because .val() refers to the value of an input field.
Your HTML inside the form should include a hidden input field:
<input type="hidden" id="word_count" name="word_count" value="0" />
Then inside your JS:
$('#word_count').val(wordCount);
All together embedded inside your function:
counter = function() {
var value = $('#msg').val();
if (value.length == 0) {
$('#wordCount').html(0);
$('#totalChars').html(0);
$('#charCount').html(0);
$('#charCountNoSpace').html(0);
return;
}
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
var totalChars = value.length;
var charCount = value.trim().length;
var charCountNoSpace = value.replace(regex, '').length;
$('#wordCount').html(wordCount);
$('#word_count').val(wordCount);
$('#totalChars').html(totalChars);
$('#charCount').html(charCount);
$('#charCountNoSpace').html(charCountNoSpace);
};
$(document).ready(function() {
$('#count').click(counter);
$('#msg').change(counter);
$('#msg').keydown(counter);
$('#msg').keypress(counter);
$('#msg').keyup(counter);
$('#msg').blur(counter);
$('#msg').focus(counter);
});
If you have INPUT fields in your form, use val()
$('#wordCount').val(wordCount)
That would work for a field like this:
Be aware that there's a difference between "id" and "class". jQuery allows you to select elements based on their properties. The "id" property gets selected with "#", just like you'd do it in CSS. So make sure you have that "id='wordCount'" defined in your hidden field.
Have a look at this http://www.hscripts.com/scripts/JavaScript/word-count.php
There are plenty of examples online, just google "javascript count words in textbox"
Some imporntant notes:
A very long string with no spaces is still 1 word so don't forget to set the max length for fields
If you are doing this as a sort of validation be aware of the fact that you can not trust a form field because it can be easily manipulated, so don't forget to check the word count on the server side after the form is submitted.
The Code that you are showing is not just javascript it also includes jquery, please make sure you included jquery
<script src = "http://code.jquery.com/jquery-1.11.1.min.js"></script>
$('#field').val('asdf'); //Sets Value of a input type="text"
$('#field').html('sadf'); //Sets the html of a div
Using javascript you use either value for a input or innerHtml for a div or other text based element
document.getElementById('field').value = 'asdfsadf';
document.getElementById('field').innerHtml= 'asdfsadf';
Also instead of using a form submit consider using jquery $.ajax(there is nothing wrong with form submits but there are benefits to knowing jquery as well such as you came make async requests
http://api.jquery.com/jquery.ajax/
You will want to use a hidden field such as the following and have it in the form
<form id="myform" action='posttome.php'>
<input type="hidden" id="wordCount"/>
<input type="submit" value="sbumit"> //Submits Form
</form>
Then set its value by using of of three methods, a an elements html, an elements value, or a javascript variable $('#wordCount').val()
$('#wordCount').val($('#wordCountSoruceDiv').html()); // Sets the value to another divs html
$('#wordCount').val($('#wordCountSourceInput').val()); // Sets the value to another inputs value
$('#wordCount').val(wordCountVariable); // Sets the value to a variable

Display Form Input as Stylized String - Javascript

I am trying to take input from a number field and display it somewhere else on the page.
Here is my HTML
<input id="dollar" type="text" name="mytextfield2" onkeyup="updateDollarDisplay();">
<div id="dollarValue"></div>
and my javascript
function convertDigitsToArray(number){
var s = parseInt(number).toString(10).split("").map(Number);
return s;
}
function updateDollarDisplay() {
var amount = $('#dollar').value;
var a = convertDigitsToArray(amount);
console.log(a[0]);
$('#dollarValue').text(a[0]);
}
Running the exact code in a javascript interpreter works fine, it gives me each digit as an element in the array. When I try to do the same through the HTML page it gives me NaN each time. Any ideas?
Fiddle here: http://jsfiddle.net/7mzo8eb5/2/ I'd like it to show to input in the grayed div on each input.
The problem is with var amount = $('#dollar').value;
value is not an attribute, but val is a function. Should be: var amount = $('#dollar').val();

Pass variable value from form javascript

Say I got a HTML form like below and want to pass the values in the textfields to JS variables.
<form name="testform" action="" method="?"
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
</form>
I've only passed values to variables in PHP before. When doing it in javascript, do I need a method? And the main question, how is it done?
Here are a couple of examples:
Javascript:
document.getElementById('name_of_input_control_id').value;
jQuery:
$("#name_of_input_control_id").val();
Basically you are extracting the value of the input control out of the DOM using Javascript/jQuery.
the answers are all correct but you may face problems if you dont put your code into a document.ready function ... if your codeblock is above the html part you will not find any input field with the id, because in this moment it doesnt exist...
document.addEventListener('DOMContentLoaded', function() {
var input = document.getElementById('name_of_input_control_id').value;
}, false);
jQuery
jQuery(document).ready(function($){
var input = $("#name_of_input_control_id").val();
});
You don't really need a method or an action attribute if you're simply using the text fields in Javascript
Add a submit button and an onsubmit handler to the form like this,
<form name="testform" onsubmit="return processForm(this)">
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
<input type="submit"/>
</form>
Then in your Javascript you could have this processForm function
function processForm(form) {
var inputs = form.getElementsByTagName("input");
// parse text field values into an object
var textValues = {};
for(var x = 0; x < inputs.length; x++) {
if(inputs[x].type != "text") {
// ignore anything which is NOT a text field
continue;
}
textValues[inputs[x].name] = inputs[x].value;
}
// textValues['testfield1'] contains value of first input
// textValues['testfield2'] contains value of second input
return false; // this causes form to NOT 'refresh' the page
}
Try the following in your "submit":
var input = $("#testfield1").val();

Categories

Resources