Coupling View and Controller in Javascript - javascript

First i have a very basic Question about coupling two input Elements. In my case it is a Slider and an input element:
<div class="userInput">
<input id="slider" type="range" min="0" max="100"/>
<input id="number" type="number" max="100"/>
</div>
js:
$('#slider').corresponding = $('#number');
$('#number').corresponding = $('#slider');
$('#slider').onchange(function(){this.corresponding.value = this.value;});
$('#number').onchange(function(){this.corresponding.value = this.value;});
So this works for me but also seems to me like a dirty hack, extending the jQuery object. The bad feeling even grows when appending the controller to jQuery Objects:
var MYController = new Controller();
$('#slider').controller = MYController;
$('#slider').onchange(function(){
this.corresponding.value = this.value;
this.controller.sliderChange(this.value);
});
I would appreciate any suggestions how this is done "the right way". I couldn't figure out a better way yet because i have a large and changing number of user inputs, each requiring its own controller Object, held in an array in my Mastercontroller Class.

Maybe you can put all the inputs inside a <form></form> tag in jsp and then call the form submit event or the serialize event. With the latter (serialize any value stored against a button would not be stored and it would need the name attribute in the jsp tags as well, so may be submit is a better option).
//jsp page
<form id="myForm" >
<input type="text" value="Enter here">
<input type="submit" value="Submit">
</form>
//js call
( "#myForm" ).submit(function( event ) {
// call the controller
});

Related

Jquery get input value from another text input value and set into hidden input value

I am new at Jquery. My User Story: I have two input form tag. One is hidden and One is Text. I need to take value from input text and set that value into hidden input and then submit the form with both value. Is it possible to do in Jquery. Here is my example code:
if ($_POST) {
$email = $_REQUEST['email'];
$username = $_REQUEST['username'];
echo "Email Value: " . $email ." And Username Value :" .$username;
}
var lap = $("emailId").val();
var test = $("userId");
test.val(test);
<form>
<input id="emailId" name="email" type="text" value="">
<input id="userId" name="username" type="hidden" value="">
<input type="submit" value="Submit" />
</form>
You don't need jQuery for this. I've provide a solution using jQuery as well as vanilla JavaScript.
jQuery Version
$(document).ready(function(){
$email = $('#email')
// Note that we are updating the hidden input value each time the
// text input value changes. We could do this less frequently by
// using the `input` or `change` event instead of the `keyup` event.
$email.on('keyup', function(e){
$('#userId').val($email.val())
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="email" id="email" />
<input type="hidden" name="userId" id="userId" />
<button type="submit" id="submit">Submit</button>
</form>
Vanilla JavaScript Version
document.addEventListener('DOMContentLoaded', function(e) {
var txtEmail = document.querySelector('#email')
var txtUserId = document.querySelector('#userId')
// Note that we are updating the hidden input value each time the
// text input value changes. We could do this less frequently by
// using the `input` or `change` event instead of the `keyup` event.
txtEmail.addEventListener('keyup', function(e) {
txtUserId.value = txtEmail.value
})
})
<form>
<input type="text" name="email" id="email" />
<input type="hidden" name="userId" id="userId" />
<button type="submit" id="submit">Submit</button>
</form>
A brief explanation of my method
Waiting for the HTML to load
Whether you're using jQuery or not, depending on how your JavaScript and HTML code is stitched together, sometimes you're HTML elements are not available when your JavaScript code runs (for example, if your JavaScript code is included in the <head> tag, which I think has become pretty uncommon these days). For this reason, I've gotten into the habit of making sure the document is ready before I reference any HTML elements. Using jQuery, this is done with the following code:
$(document).ready(function(){
// The code here (inside this function) will be executed after the HTML finishes loading.
})
With vanilla JavaScript, the code looks like this:
document.addEventListener('DOMContentLoaded', function(){
// The code here (inside this function) will be executed after the HTML finishes loading.
})
Making Updates As Soon As Possible
In addition, my code updates the hidden input value after the text input value has changed, rather than waiting for the form to be submitted. Either option may be perfectly acceptable for a given situation. I am in the habit of updating things like these as soon as possible; if in the future, I write some JavaScript code that is expecting the value of these to input controls to be equivalent, and that code runs before the form is submitted, I'll probably have a bug in my code. Hence, I find it safer to just update as soon as the change occurs.
As per jquery documentation You forgot to use # in your both selectors. You should use:
var lap = $("#emailId").val();
var test = $("#userId");
test.val(lap);

JavaScript watch form fields and set session cookie

I'm a little rusty as it's been a long time since I've used much JavaScript. I'm wanting to watch all input fields within a form for the mouseout event and set a session cookie to store that value. Is there a neat way I can do this so I can watch all form fields within a form and avoid needing to watch one field at a time — I'm anticipating there could be a large number of fields so I want an efficient way to target them.
Say my form is:
<form action="#">
<input id="form1_name" name="name" class="s_input" required="required" type="text">
<input id="form1_email" name="email" class="s_input" required="required" type="text">
<textarea id="form1_message" name="message" class="s_input" cols="30" rows="4" required="required"></textarea>
<input id="form1_submit" name="submit" class="s_input" value="Send" type="submit">
</form>
This is as far as I got with my JS, it currently fails with:
//get all the fields in question
var inputFields = document.getElementsByClassName('s_input');
//can see the inputs collected in an array
console.log(inputFields);
//fails
inputFields.addEventListener("mouseleave", function( event ) {
});
I get an error of:
TypeError: inputFields.addEventListener is not a function [Learn More]
document.getElementsByClassName('s_input'); Creates an array so to add anything to each element of the class s_input you need to loop over the collection.
Something like this should work:
for (i = 0; i < inputFields.length; i++) {
inputFields[i].addEventListener("mouseleave", function( event ) {
//event code here
});
}
Edit: Probably better to use "blur" event as mouseleave wont work if user is on a touch device or using keyboard only to tab through inputs.
Instead of attaching an event listener for blur you can do this:
<input onblur="callYourFunction()" id="form1_name" name="name" class="s_input" required="required" type="text">

Mix static text and scope's variable inside directive

I've created a simple form with a name:
<form novalidate ng-controller="TestController" role="form" name="testForm">
<input type="number" min="10" name="textForm" value="4">
<input type="submit" ng-click="validate(testForm)">
</form>
and then I've created a controller:
angular.module("testModule", []).controller("TestController", function($scope){
$scope.validate = function(form){
alert("inside the function validate()");
}
});
This works correctly (since the alert pop up on screen) as you can see here.
Now I've added a variable to the scope $scope.testNumber = 5; and appended this version to the form's name name="testForm{{testNumber}}">and do the same thing on the input submit of the form <input type="submit" ng-click="validate(testForm{{testNumber}})">. And this doesn't work, since I can't see any alert, as you can see here. The syntax is not correct, but how can achieve what I want to do?
Since your ng-click is a function with a param, you need to concat the variables. So testForm + testnumber should give you the desired result.
Controller
angular.module("testModule", []).controller("TestController", function($scope){
$scope.testNumber = 5;
$scope.validate = function(form){
alert("inside the function validate()" + form);
}
});
Html
<form novalidate ng-controller="TestController" role="form" name="testForm{{testNumber}}">
<input type="number" min="10" name="textForm" value="4">
<input type="submit" ng-click="validate(testForm + testNumber)">
</form>
And a plunker to demo the changes
When you use the name attribute of the form element, you are publishing the form instance into the controller scope.
Thus, you will have a property testForm which you can access with $scope.testForm. (Documentation)
Strictly speaking, you don't have to pass the form to the function that you call when you submit as it is accessible from the scope.
However, if you do wish to carry it out, I suggest that you separate the code from the markup - define a scope property in your controller that will hold the name of the form like so:
$scope.myForm = 'testForm1';
You can then use this in your markup as:
<form name="{{myForm}}">
...
<input type="submit" data-ng-click="validate(myForm)"/>
</form>
You can easily create an array of form names and use them in your markup (by indexing them) without having to do string concatenation and cluttering your markup.

How to modify form fields with JavaScript?

I have a big form with lots fields, now I want to use JavaScript to simplify the fields, that means, pre process and delete some of the fields with JavaScript then return a new processed field.
For example, I have fields in the form like plot_country, plot_state, plot_city, what I want to do is to precalculate the location_# from the country, state, city in JavaScript, and return the GET fields just contain location_#.
In this way the url will be simplified, and the server can directly use the location_# and it doesn't need to process the location combinations any more.
Does anyone have some ideas? Thanks!
Try something like this:
<form id="location_form">
<input type="text" id="plot_country">
<input type="text" id="plot_state">
<input type="text" id="plot_city">
<input type="hidden" id="location">
<input type="submit">
</form>
<script type="text/javascript">
$( "#location_form" ).submit(function( event ) {
$('#location').value($(this).serialize());
$('input[type=text]').remove();
});
</script>

JavaScript did not receive value in this.form

I am using a three part code below:
First part of the code: Basically a javascript function changeSearchEngine will be triggered when user select Google.
<p id="searchbox">This paragraph will change once javascript is triggered</p>
<form align=right>
<select name="searchengine" onchange="changeSearchEngine(this.form)">
<option value="google">Google</option>
</select>
</form>
This is my changeSearchEngine function in javascript.
function changeSearchEngine(form)
{
var searchEngine=form.searchengine.value;
if (searchEngine=="google")
{
var url_google='<form method="get" action="http://www.google.com/search" onsubmit="submitGoogle(this.form)" target="_blank"><input type="text" name="q" size="31" maxlength="255" value="" /><input type="submit" value="Google Search"/></form>';
document.getElementById("searchbox").innerHTML=url_google;
}
}
At this point of time, all is working well. When I select Google, the searchbox for google appears. I can search and everything.
Notice there is a onsubmit="submitGoogle(this.form)" right? I need to save what the user search terms into SQL table. So I have this javascript function below to capture what user have type:
function submitGoogle(form)
{
alert("Inside submitGoogle function");
var searchterm=form.q.value;
alert(searchterm); //to test. this part didnt capture the value.
}
I managed to invoke the submitGoogle function BUT however I can't retrieve the value of q despite using searchterm=form.q.value. What did I do wrong here?
In your onsubmit handler, you are passing this.form. But, this already refers to the form since it is the form itself that triggers the submit event. Form fields have a form property, but the form itself does not have a form property. So, just change your handler to pass this instead of this.form.
http://jsfiddle.net/fmqNj/
onsubmit="submitGoogle(this)"
Okay I found one possible solution. Let me answer my own question.
In changeSearchEngine(form) function, i change to this:
var url_google='<form method="get" name="googleform" action="http://www.google.com/search" onsubmit="submitGoogle(this.form)" target="_blank"><input type="text" name="q" size="31" maxlength="255" value="hello" /><input type="submit" value="Google Search"/></form>';
In submitGoogle(form) function, i change to this:
var searchterm=document.googleform.q.value;
But I still like others to comment on my solution whether it is not elegant or not within the practice. :D

Categories

Resources