Dynamic Client Script - javascript

I need to write a java script. This is supposed to validate if the checkbox is selected in the page or not. The problem here is that the check box is inside a grid and is generated dynamically. The reason being the number of check box that need to be rendered is not know at design time. So the id is know only at the server side.

Here is a thought:
As indicated by Anonymous you can generate javascript, if you are in ASP.NET you have some help with the RegisterClientScriptBlock() method. MSDN on Injecting Client Side Script
Also you could write, or generate, a javascript function that takes in a checkbox as a parameter and add an onClick attribute to your checkbox definition that calls your function and passes itself as the parameter
function TrackMyCheckbox(ck)
{
//keep track of state
}
<input type="checkbox" onClick="TrackMyCheckbox(this);".... />

You have to generate your javascript too, or at least a javascript data structure (array) wich must contain the checkboxes you should control.
Alternatively you can create a containing element, and cycle with js on every child input element of type checkbox.

If it's your only checkbox you can do a getElementsByTagName() call to get all inputs and then iterate through the returned array looking for the appropriate type value (i.e. checkbox).

There is not much detail in the question. But assuming the the HTML grid is generated on the server side (not in javascript).
Then add classes to the checkboxes you want to ensure are checked. And loop through the DOM looking for all checkboxes with that class. In jQuery:
HTML:
<html>
...
<div id="grid">
<input type="checkbox" id="checkbox1" class="must-be-checked" />
<input type="checkbox" id="checkbox2" class="not-validated" />
<input type="checkbox" id="checkbox3" class="must-be-checked" />
...
<input type="checkbox" id="checkboxN" class="must-be-checked" />
</div>
...
</html>
Javascript:
<script type="text/javascript">
// This will show an alert if any checkboxes with the class 'must-be-checked'
// are not checked.
// Checkboxes with any other class (or no class) are ignored
if ($('#grid .must-be-checked:not(:checked)').length > 0) {
alert('some checkboxes not checked!');
}
</script>

Related

How to get POST form data that have dynamic IDs?

I have checkboxes inside a form. These checkboxes are a list of persons dynamically created since this list depends on who is logged in. Like, for a supervisor view, it will only list your subordinates.
I'm not sure if I'm missing something but the docs and other answers in SO are all saying that you have to have the id of the input in order to retrieve the form data but in my case, I used the person's ID in the list to come up with the name of the checkbox element. So my checkbox names are like input-{{person_id}}
Now in the post method, I'm not sure how to retrieve the checkboxes in the form. Tried using self.__dict__ but I can't seem to find anything that I can use
link1 - this specifies the name
link2 - this also says that the ID should be pre-determined
link3 - docs also say that if the parameter is not included, an empty list would returned
Maybe there is a workaround where I just get all the elements in the form and make them seen in tornado? Using javascript maybe?
I'm mistaken, it seems that if you use the same name for a checkbox element for all the dynamic checkboxes you create, then when you submit it to the tornado web handler, it will get the values of all those checkboxes that have that name.
the values are retrieved by using the get_arguments
Is this how you mean?
HTML
<form>
<input type="checkbox" id="box1" name="Name1" checked>
<label for="box1">Name 1</label>
<input type="checkbox" id="box2" name="Name2">
<label for="box2">Name 2</label>
</form>
jQuery
$("form input[type='checkbox']").each(function() {
console.log($(this).attr('name'))
})
Output
"Name1"
"Name2"
You can loop through the request.body_arguments attribute; it's dict which maps arguments names to lists of values (to support multiple values for individual names).
class MyHandler(tornado.web.RequestHandler):
def post(self):
for key, value in self.request.body_arguments.items():
print(f"key {key} has value: {value}")
...
There are also arguments (holds both query and body args) and query_arguments (holds only query args) attributes; you can check the docs here.

condition for an MVC checkbox in javascript

I have a checkbox in an MVC project called:
#Html.CheckBox("ShowAll", true)
and then in my js I want to check if the checkbox is checked or not.
Something like
function checkboxAll(item)
{
if ((showAll).isChecked)
{
//do stuff
whats the best way? I cant seem to get the syntax right
Thanks
}
}
When using #Html.Checkbox the first parameter is the html attribute "name" that will be applied when the checkbox is created.
If you retrieve a DOM element from a html attribute you can use the following jquery:
var isChecked = $("[Name='ShowAll']").val()
P.S. I can't guarantee this is correct and will edit comment later if it is.
So if you write #Html.CheckBox("ShowAll", true) this renders a checkbox with below properties.
<input checked="checked"
id="ShowAll"
name="ShowAll"
type="checkbox"
value="true" />
Also it generates a hidden input like this:
<input name="CheckBox" type="hidden" value="true" />
Now you know how to get a field by name or id in jquery.
access value by
$("input[name='ShowAll']").val()
or is checked
$("input[name='ShowAll']").is(':checked')
or by pure js var chkbox = document.getElementsByName("ShowAll");
See the msdn page for complete overloads.

How to prevent checking checkbox when added dynamically to a div?

so I've been struggling with this issue.
I want to add a checkbox into a div dynamically by clicking a button. Let's say I already have 2 checkboxes in the div, then I uncheck those 2. When I click the button, the checkboxes become 3 (which is what I want), but all those 3 will be checked. What I want is when I add a checkbox, the other checkbox(s)' checked state remain the same as before.
Here is my code (http://jsfiddle.net/gr2o47wt/4/):
HTML:
<div id="chkbox_container">
<input type="checkbox" checked>Check<br />
</div>
<input type="button" value="Add CheckBox" onClick="addCheckBox();">
JavaScript:
function addCheckBox() {
txt = "<input type=\"checkbox\" checked>Check<br />";
document.getElementById('chkbox_container').innerHTML += txt;
}
Thanks in advance for your answers! :)
You can use insertAdjacentHTML() rather than manipulating the innerHTML:
<input type="button" value="Add CheckBox"
onClick="document.getElementById('chkbox_container').insertAdjacentHTML('beforeend','<input type=\'checkbox\' checked=\'checked\' />Check<br />');">
JS Fiddle demo.
The problem you had was that the original HTML (as returned by innerHTML) is from the source of the page, not the DOM; and therefore the checked/unchecked nature of the checkbox originally in place was restored.
insertAdjacentHTML() simply adds the HTML string in the specified place ('beforeend' in this case).
More or less as an aside, it's worth trying, where possible, to keep your event-handling outside of your HTML elements; and binding those event-handlers in the JavaScript itself. This makes for somewhat easier maintainability, and would lead to code like the following:
// note that I gave the button an 'id' for simplicity:
var button = document.getElementById('addCheckboxes');
button.addEventListener('click', function () {
document.getElementById('chkbox_container').insertAdjacentHTML('beforeend', '<input type=\'checkbox\' checked=\'checked\' />Check<br />');
});
JS Fiddle demo.
Finally, some of your HTML is invalid (or at least erroneous), an <input /> is a void element, it can have no descendants; therefore it either has no closing tag (just: <input>) or self-closes (<input />).
Further, the text beside the checkboxes is a little misleading, usually with an HTML form the text beside the <input /> will focus that input; that's achieved by using a <label> element to associate the text with the control, for example:
<label><input type="checkbox" /> click</label>
JS Fiddle demo.
Or:
<input type="checkbox" id="inputElementID" />
<label for="inputElementID">click</label>
But this latter form does require the dynamic generation of ids (which is a little beyond the scope of this question).
References:
insertAdjacentHTML().

Setting the value of multiple inputs with the same id using jQuery?

Considering the following HTML:
<form id="upvoteForm" method="post" action="/post/upvote">
<input type="text" name="post_id" id="post_id"/>
</form>
<form id="downvoteForm" method="post" action="/post/downvote">
<input type="text" name="post_id" id="post_id"/>
</form>
<input type="hidden" id="_postid" value="1"/>
I'm trying to set the two input fields with the name post_id to to value from _postid using this JavaScript and jQuery:
$(document).ready(function() {
$('#post_id').val($('#_postid').val());
});
However, as you can see in this jsFiddle, it's only setting the value of the first one. How do I set the value of both of them? I thought the selector would end up grabbing both.
Now, I realize you might be wondering why I have two forms on this page. The basic reason is I have button inputs that I've styled the way I want but then I use the onclick to call the submit of the appropriate form here. I am ultimately going to be leveraging AJAX here, but that's coming later.
id is always unique. you cannot select 2 elements with same id. select by name
$(document).ready(function() {
$('input[name=post_id]').val($('#_postid').val());
});
Having two HTML elements with the same ID is illegal and will cause undefined behavior such as what you're experiencing. Using the same name is valid, however. Therefore you could use a selector like $('form > input[name=post_id]'), which would look for an input inside of a form with the name attribute set to post_id.

Hidden fields in AngularJs

How do I access hidden fields in angular? I have an app, where I want to submit a form for each of items in the list. The form is simple - it has submit button and a hidden field holding the ID value. But it does not work. The value is empty.
I updated the default angular example to display the situation - the todo text is in hidden field.
http://jsfiddle.net/tomasfejfar/yFrze/
If you don't want to hardcode anything in your javascript file, you can either load it via AJAX, or do:
<input type="hidden" name="value" ng-init="model.value=1" value="1">
this way, you can keep the form functionality with JS off, and still use the hidden field in AngularJS
If you want to pass the ID from the ng-repeat to your code, you don't have to use a hidden field. Here's what I did:
For example, let's say I'm looping through a collection of movies, and when you click the "read more" link it will pass your ID to your JS code:
<ul>
<li ng-repeat="movie in movies">
{{movie.id}} {{movie.title}} read more
</li>
</ul>
Then in your JS code, you can get the ID like this:
$scope.movieDetails = function (movie) {
var movieID = movie.id;
}
In your simpler fiddle, the problem can be fixed by using ng-init or setting an initial value in the controller. The value attribute won't effect the ng-model.
http://jsfiddle.net/andytjoslin/DkMyP/2/
Also, your initial example (http://jsfiddle.net/tomasfejfar/yFrze/) works for me in its current state on Chrome 15/Windows 7.
You can do something like this.
It is a dirty trick, but it works (like most dirty tricks ;-)
You just use the form name as Your hidden field
and always give the form the id "form"
<!doctype html><html ng-app><head>
<script src="angular-1.0.1.min.js"></script>
<script>
function FormController($scope) {
$scope.processForm = function() {alert("processForm() called.");
$scope.formData.bar = "";
try {$scope.formData.bar = document.getElementById("form").name;}
catch(e) {alert(e.message);}
alert("foo="+$scope.formData.foo+ " bar="+$scope.formData.bar);
};
}
</script></head><body>
<div ng-controller="FormController">
<form name="YourHiddenValueHere" id="form">
<input type="text" ng-model="formData.foo" />
<button ng-click="processForm()"> SUBMIT </button>
</form>
</div></body></html>
This allows You to use ONE Controller for ALL forms and send
them to ONE server script.
The script than distinguishes by the
form name (formData.foo) and knows what to do.
The hidden field names the operation in this scenario.
Voila - You have a complete application with as
many forms You want and one server script
and one FormController for all of them.
Simpler:
<input type="hidden" name="livraisonID" value="{{livraison.id}}"/>
It works!
Use ng-binding="{{employee.data}}". It will work properly.
I have to correct (improve) myself:
You can do it more elegantly:
<form>
<input type="text" ng-model="formData.foo" />
<input type="hidden" id="bar" value="YourHiddenValue" />
<button ng-click="processForm()"> SUBMIT </button>
</form>
and then in the JavaScript controller:
$scope.formData.bar = "";
try {$scope.formData.bar = document.getElementById("bar").value;}
catch(e) {alert(e.message);}
alert("foo="+$scope.formData.foo+ " bar="+$scope.formData.bar);
So you can have as many hidden fields as you like.

Categories