I currently have a form that is displaying fields that I do not want it to. There are 3 input fields associated with one form and the same form is being rendered multiple times.
I have my template set up to check for when this was only one value. I need to change it so the template will check for all of the values present & then decide to render.
So for example,
I have,
Div_id_form-0-x,
Div_id_form-0-y,
Div_id_form-0-z,
Div_id_form-0-location__location_category__requires_coordinates
What selector can I use to grab all of these to use in my template?
I need to grab them for each form. Where it says form-0 I have several of these forms repeating.
Then in HTML I have something like this.
$(function () {
// Determine weather we are in a modal window.
var context = $("#{{ contextId }}-form");
console.log("this is the {{ contextId }}" )
// Show required coordinates if location category requires them.
context.find("#id_location__location_category__requires_coordinates").change(function () {
if (context.find("#id_location__location_category__requires_coordinates").val() == 'Y') {
context.find('#id_needs_coordinates').removeClass('hide');
} else {
context.find('#id_needs_coordinates').addClass('hide');
}
});
});
Right now this is only checking for one value to determine whether to hide. I need it to check all of these for this value. Which is why I'm looking for a Jquery selector that can do such.
If you want a selector for IDs, you can use:
$("#Div_id_form-0-x, #Div_id_form-0-y, #Div_id_form-0-z, #Div_id_form-0-location__location_category__requires_coordinates")
Please see: https://api.jquery.com/id-selector/
Update
In the future, please clarify the entire issue and provide a proper example.
You can use the Attribute selectors.
$("[id^='Div_id_form-']")
This will select all IDs like:
Div_id_form-0-x
Div_id_form-1-x
Div_id_form-2-x
You will then select all of those elements.
See More: https://api.jquery.com/category/selectors/attribute-selectors/
I have a web document that has its fields populated dynamically from c# (.aspx.cs).
Many of these fields are TextBox or HtmlTextArea elements, but some are Checkbox elements.
For each of these I have the ID attribute populated on creation of the field, as well as using .Attributes.Add("onchange","markChanged(this.id)")
This works great on all the fields except Checkbox. So I created a markCheckChange as I discovered that the Checkbox won't accept style="backgroundColor:red" or .style.backgroundColor = "red" type arguments.
I also added an alert and found that the Checkbox is not actually passing the this.id into the parameter for markCheckChange(param) function.
As a result I am getting errors of the type:
unable to set property of undefined or null reference
Why and what is the difference between these controls, and is there a better way to handle this?
I just reviewed the inspect element again, and discovered that the Checkbox control is creating more than an input field of the type checkbox, it is also wrapping it in a span tag, and the onchange function is being applied to the span tag (which has no id) and not to the input tag that has the checkbox id. Whereas for TextBox and HtmlTextArea the input tag is put directly within the cell/td tag, no some arbitrary span tag.
So now the question becomes how to get the onchange function to apply to the input tag for the checkbox rather than the span tag encapsulating it?
Per request:
function markChange(param) {
if (userStatus == "readonly") {
document.getElementById("PrintRecButton").style.display = "none";
document.getElementById("PrintPDFButton").style.display = "none";
alert("Please login to make changes.\n\nIf you do not have access and need it,\n contact the administrator");
exit();
}
else {
document.getElementById(param).style.backgroundColor = "teal";
saved = false;
var page = document.getElementById("varCurrentPage").value;
markSaveStatus(page, false);
}
}
So far the markCheckChange is about the same, until I get it to pass the id correctly, I won't be able to figure out the right way to highlight the changed checkboxes.
I found an alternative.
As I mentioned in the edit to the question, the inspect element feature revealed that the CheckBox type control was creating a set of nested elements as follows:
<span onchange="markChange(this.id)">
<input type="checkbox" id="<someValue>">
<label for="<someValue>">
</span>
Thus when the onchange event occurred it happened at the span which has no id and thus no id was benig passed for the document.getElementById() to work.
While searching for why I discovered:
From there I found the following for applying labels to the checkboxes:
https://stackoverflow.com/a/28675013/11035837
So instead of using CheckBox I shall use HtmlInputCheckBox. And I have confirmed that this correctly passes the element ID to the JavaScript function.
In my application users can edit information for their reservation but I don't want them to change the type of reservation. So I have thought to load a page with a select menu displaying the type of reservation but it is also disabled. What I would like to happen is that on page load if the select menu is disabled then the relative elements are showed according to the selected but disabled type. Reading the documentation this is what I have thought I need:
jQuery("#tipologia_piazzola").load(function(){
alert("something");
if (this.value == "mensile" && this.is(":disabled")) {
jQuery(".both").show();
jQuery(".mensile").show();
jQuery(".giornaliera").hide();
}
});
Obviously I have inserted it inside the ready function but neither the alert nor the html elements appear. Is this the correct way? Or, how can I reach my goal?
You need to use jQuery(this) instead of this to call is(':disabled') function because it need jQuery object and not javascript object. Also use document.ready as shown below to ensure that all DOM element is ready.
jQuery(document).ready(function(){
var $this = jQuery('#tipologia_piazzola');
if ($this.val() == "mensile" && $this.is(":disabled")) {
jQuery(".both").show();
jQuery(".mensile").show();
jQuery(".giornaliera").hide();
}
});
NOTE : - please exclude document.ready if you have it already and put above code in your existing document.ready
I would like to disable a button
<BUTTON name="Next Page" onClick="Next()" VALUE="NextPage">NextPage</button>
based on a javascript variable
var opening = 0;
function Next()
{
var currentdoc = viewONE.getDocIndex();
if (currentdoc == 5)
{
**[DISABLE BUTTON]**
}
what is the javascript code please?
Background information:
Simply browsing through documents using a next and previous buttons. on the first document i want the "previous" button greyed out and on the the last document i want the "next" button greyed out.
Appologise for any incorect terms, newb and never asked this type of question before.
you are welcome to correct my term in a constructive way... need to learn.
Sam's solution is good and will disable the action of the button but won't disable it functionally.
You can disable the input button by changing changing the "disabled" attribute, but you really need to give your button a valid identifier first (I wouldn't even want to let jQuery select it by name due to the space).
jQuery would look something like this:
$('#yourbuttonid').attr('disabled','disabled');
Regular Javascript would be the following:
document.getElementById('yourbuttonid').disabled = true;
Here's an example on JSBin.
All you need to do is:
var opening = 0;
function Next()
{
var currentdoc = viewONE.getDocIndex();
if (currentdoc == 5)
{
return; //This will end the function immediately.
}
}
In terms of greying out buttons, can you not add / remove classes to show different versions of the buttons? We would need more to see your html, and what you have tried so far to help further.
Tutorial on return
I am not a web-developer and want to understand the better way to pass variables. In the past I have used various ways to pass things to java script functions. I have never used forms as I always associated them with server and databases. I have a website in which user selections change the contents of the website.
I am wondering if you can use forms without any server just as a way to pass a few things to a javascript function where they are used to change the page content. For basic example, if someone selects male the page background becomes blue, if they choose female the background becomes pink. Would forms be the way to go and just onsubmit call a javascript function? How would I actually pass the form contents to the javascript function?
Yes you absolutely can use forms/inputs/any kind of html element and never talk to a server, just don't expect to store that data! You're right about using events (like the onsubmit one you mentioned) to trigger Javascript functions.
Here is a quick and dirty example (heavy on the dirty) that does sorta kinda what you'd like. Note that instead of waiting for the form to be submitted before the color change, I go ahead and do it immediately after they choose a gender from the dropdown.
http://jsfiddle.net/wG8K4/1/
You wouldn't pass the parameters. You could have "onsubmit" call a javascript function, and then within the function use javascript to access the actual controls that the user has selected. You could use the GetElementById function to retrieve a certain element, and then determine the value of that element.
If all you wanted to do was change the background color, you could use javascript to change the backgroundColor property of the body tag or any tag on the page.
You'd have to remember to return false from your function, though -- otherwise, the form would be submitted.
You don't need servers / databases to use forms. Forms are simply a method from passing variables from one file to another, regardless if that is an html file or some php script or what have you. If you stick to using GET forms, your form will naturally pack its data into the URL of your page at which time you can access them. For instance (borrowed from http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/):
<script language="javascript">
function $_GET(q,s) {
s = s ? s : window.location.search;
var re = new RegExp('&'+q+'(?:=([^&]*))?(?=&|$)','i');
return (s=s.replace(/^?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;
}
var usersName = $_GET('username');
if(typeof(usersName)!='undefined'){
document.write('<h1>Hi there, '+usersName+'</h1>');
}
</script>
<form>
<input type="text" name="username" />
<input type="submit" value="Say my name" />
</form>
The basic event you're going to look for is the form's submit event. If you're okay with just using event handlers, you can just do something like this:
var myForm = document.getElementById('myForm');
myForm.onsubmit = function () {
// ...
};
Because you're just using JavaScript, you don't want the form to actually submit. (Side point: Because you're using JS, you should just build this form and add it to the page with JS, but that's a completely different issue.) You can cancel the form's default action like so:
myForm.onsubmit = function () {
// ...
return false;
};
Before we get into accessing data, make sure that you grab the elements you're going to need. It makes things a little faster, because you don't have to select the entire element from the DOM every time the form is submitted. For example:
var myForm = document.getElementById('myForm'),
myTextField = document.getElementById('myTextField'),
mySelectBox = document.getElementById('mySelectBox'),
// ...
Depending on what kind of form elements you have, there are different ways to access their data. Text inputs, text areas, and select boxes are really easy:
var textValue = myTextField.value,
selectValue = mySelectBox.value;
Radio buttons and check boxes are a little more complicated, because you have to go through every single one and see which one(s) is/are checked and which one(s) isn't/aren't, like so:
var isOneChecked = checkboxOne.checked,
isTwoChecked = checkboxTwo.checked;
Going with your example of blue/pink background, you would probably want something similar to this:
var myForm = document.getElementById('myForm'),
maleBox = document.getElementById('maleBox');
myForm.onsubmit = function () {
var isMale = maleBox.checked;
if (isMale) {
document.body.style.backgroundColor = 'manlyBlue';
} else {
document.body.style.backgroundColor = 'sexistPink';
}
};
Notes
If you do decide to go with event handlers, keep in mind that only one can be applied to your form at a time. If you want to attach a different function to the submit event as well, you'll have to go with event listeners, which is a completely different ball game and introduces problems of its own.
The final example only checks the value of the "I'm a guy" element, because (presumably) you're using radio buttons and you only have two options. If "I'm a guy" is not checked, then the other one should be. But if the form starts out with neither option checked, then that could be considered a bug.
The final example also uses inline styles to change the body's background color. It hurt me to type. A much more bearable method would be to add/remove classes as needed, but again, that's kind of beyond the scope of this question.
Form elements can be used as a form of global variables - holding state that can be used and shared by all the javascript in a single page.
However, this could result in brittle and difficult to understand code.
I suggest keeping with passing parameters to functions, so long as you are in the context of a single page.
If you need to pass data to another page, then forms can make life easier - using a GET form, the values on the form will be passed to the page referenced in the form action attribute as key-value pairs. If you use the POST method they will be transferred in the headers.
If your desire is to iterate through form elements using Javascript you can easily do this using the DOM since the form will have a length property and each input will be represented as an index of this array-like object:
So for:
<form id="f" action="">
Male<input type="radio" name="gender" value="male" />
Female<input type="radio" name="gender" value="female" />
<input type="submit" value="submit" />
</form>
You could do something like this:
var f = document.getElementById('f');
f.onsubmit = function (e) {
e = e || window.event;
var et = e.target || e.srcElement,
gender;
if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; }
for (var i = 0, il = et.length; i < il; i++) {
if (et[i].name = 'gender' && et[i].checked) {
gender = et[i].value;
}
}
if (gender == 'male') {
document.body.style.backgroundColor = 'cyan';
} else if (gender) {
document.body.style.backgroundColor = 'pink';
}
};
See example →