javascript cannot call an element in array - javascript

Ok, let me explain more... the goal is to make the checkbox checked if there's a change on select. The actual code was:
function checkit(date)
{
document.forms[0].date.checked = true;
}
<input type="checkbox" name="date[]" value="2008-08-14">Aug 14, 2008<br>
<select name="slot[]" size="1" onchange="checkit(date[]);"/>
<option value="2008-08-15;0900;1700">9am to 5pm</option>
<option value="2008-08-15;1330;1730">1:30pm to 5:30pm</option>
</select>
<input type="checkbox" name="date[]" value="2008-08-15">Aug 14, 2008<br>
<select name="slot[]" size="1" onchange="checkit(date[]);"/>
<option value="2008-08-15;0900;1700">9am to 5pm</option>
<option value="2008-08-15;1330;1730">1:30pm to 5:30pm</option>
</select>
<input type="checkbox" name="date[]" value="2008-08-16">Aug 14, 2008<br>
<select name="slot[]" size="1" onchange="checkit(date[]);"/>
<option value="2008-08-15;0900;1700">9am to 5pm</option>
<option value="2008-08-15;1330;1730">1:30pm to 5:30pm</option>
</select>
In PHP, if it sees a variable with [ ], it automatically creates an array. In Javascript, I expected that Javascript would recognize the [] and execute based on the current element. For example, if I select a value in the second checkbox, it should fire an event to check that element box. I don't want to name the variable like date1, date2, date3, date4... I hope this clarifies more. I know I am missing out something... I tried "this" keyword to make it "this current element" but it doesn't seem to work but it could be that I used the improper syntax.
What I expected was that onchange event, it should fire its argument which is "date[]" but I would assume that Javascript should know which element in date[] it will use instead of expliciting calling it date[1] and so on. The checkit function gets the "date[]" name and checks that date[] checkbox.
BTW, many thanks for the supplementary answers (I learned something new!)

It doesn't work because (as dreas said) your HTML-code has errors and you are naming your variables in a way that conflicts with javascript syntax.
The name of your input is date[1] and the [ and ] have special meaning in javascript code.
In this code:
document.forms[0].date.checked = true;
you are trying to access the documents first form (document.forms[0]) and then tries to access a field called date, but there aren't any. According to your HTML-markup you have fields called "date[1]", "date[2]" and "date[3]".
But you can't access them like this:
document.forms[0].date[1].checked = true;
Why? Because date[1] tries to index the date with 1, and in this case your date is not an array.
You can access it if you enclose it in quotes:
document.forms[0]["date[1]"].checked = true;
Note that now "date[1]" is used as a string.

What exactly are you trying to do with this code ?
According to your piece of code (which has some syntax errors), you are checking a checkbox, then calling a js function that will check the checkbox again...?
What exactly are you trying to achieve?
Try this code:
function checkit(date)
{
var date = document.getElementById(date);
date.checked = true;
}
<input type="checkbox" id="date[1]" value="2008-08-14" onchange="checkit('date[1]')");/>Aug 14, 2008<br />
<input type="checkbox" id="date[2]" value="2008-08-14" onchange="checkit('date[2]')");/>Aug 14, 2008<br />
<input type="checkbox" id="date[3]" value="2008-08-14" onchange="checkit('date[3]')");/>Aug 14, 2008<br />

PHP has the syntax arr[] = something to put something at the next available index in an array.
Javascript doesn't have that syntax; if you want to put something at the next available index in an array use arr.push(something) instead.
But the portion of your example you're referring to is in HTML, not Javascript. Javascript accesses it but the form fields themselves are created in HTML... so you have to give it your own name rather than an automatically-incremented name.
If you are creating the HTML dynamically through DOM calls (e.g. for each input element, document.createElement('input'), assign attributes and then appendChild() to the main form), then you could automatically name the form fields... but that's a whole other method of generating HTML & has a bunch of pitfalls to watch out for.

First, you're wanting to use a PHP-specific feature in Javascript. No, there is no such feature so far as I can tell.
Second, I'd strongly advise not using HTML input names like "date[1]" ... that might be legal HTML (I'd have to try it in a few browsers to be sure it was effectively allowed), but it is almost 100% a likely source of errors in the maintenance cycle.
I'm assuming this code is either auto-generated for you or you just want to take a blok and copy/paste in your editor. If it is the former, I'd name the elements "date_1" in the autogen code and be done with it. If the latter then you can either maintain the number in your code (ie, manually type in date_1 through date_257) or use a Javascript document.write call to generate the HTML with less effort. I'd ONLY do the latter (document.write out HTML) if there is really no other way. If you're talking about 10-25 copies, handling this manually by hand is less likely to have a problem than using document.write; if you have more than 25 such instances then maybe it makes sense to automate the element generation.

Related

Setting Default value of input textbox in Jquery EasyUI dialog

I have googled and looked throughout the whole documentation and could not figure out why value of input text is not shown. I am using FireFox latest version and below is what I have done so far.
<input name="amount" class="easyui-validatebox" id="d_amount" value="">
In regular html or php page we can give value="300" to set default value, but in EasyUI, it is not possible. So I was thinking possible alternative like below:
<script>
var m = '300';
document.getElementById("d_amount").value.innerHTML=m;
</script>
Nothing is shown and I am not getting any error. Any EasyUI expert, please help me.
NOTE: this input field is inside the dialog
To set the default value, you have to set the value attribute. However, that does not necessarily update the value property so you need to do both. So given:
<input name="amount" class="easyui-validatebox" id="d_amount" value="">
set the default value by setting the value attribute:
var input = document.getElementById('d_amount')
input.setAttribute('value', 'whatever');
now set the value property:
input.value = 'whatever';
Note that you can also get a reference to the input as a member of the form that it's in:
var input = document.formName.d_amount;
Use the below code
$("#d_amount").numberbox({
min:0,
precision:2,
value:300
})
Reference : numberbox
Or try this one
$("#d_amount").textbox({
buttonText:'Search',
iconCls:'icon-man',
iconAlign:'left',
value:"300"
});
Reference : textbox
use this code to set the value inside $(document).ready(function(){}
....
$("#d_amount").numberbox('setValue','300');
....
if still not working, just try to set name and id as the same name and id
<input name="d_amount" class="easyui-validatebox" id="d_amount" value="">
I am always working with this numberbox and it's working
I have found your thread because I am also having the same issue and I have just across this thing today. Your case is a little bit different (maybe) then my case because you want to set the default which can be changed by the user later (I believe). In my case, the value will be fixed (will not be changed) so I have applied a trick and hopefully it can give some ideas to you and others who are having same issue. Please refer below:
In first page says pageA.php:
<select name="myThing" id="myThing">
<option value="Your Desired Value" selected="selected">Something</option>
</select>
Still in the same page, under your $(document).ready( function(){ put the code below:
$("#myThing").val($("#myThing option:first").val());
That code is to make sure your desired value appears at the first row in the drop down. I say this because in EasyUI it seems when I use drop down and put single option, the first row will be blank and the second row will hold your input. So that is the trick to ensure your desired value appears on top and selected. Put the select under the form then during normal post, you will be able to get the value of it in the posted page. Enjoy. Thank you.
Suggestion: if your value can be changed by user, use placeholder and you can hide the default value from user using my trick.
try this
document.getElementById("d_amount").value=m;
you don't need innerHTML
I found the answer here. The trick is to use the code inside $(function(){});
$(function(){
var m=300;
$('#d_amount').textbox('setValue', m);
});
I too had this problem and it was solved using the following
First my input was in the form like this:
<input name="hostFirstName" id="hostFirstName" class="easyui-textbox">
I needed to load content from the db then pre-fill the input with this data so the user could edit the content.
I used the following javascript.
NOTE: i didn't hide this away inside an anonymous function() and it is working. I tested this first from the F12 console to make sure it was working before changing my code.
//populate with existing data
$('#hostFirstName').textbox('setValue', "Is this working?");
The docs on jeasyui.com don't provide this example when you look at the textbox api reference. But they do provide an example when looking at the combobox (http://www.jeasyui.com/documentation/index.php#) the combobox and textbox use the same setValue method.
Hopefully this works for you like it does for me.

Javascript variable equal a textbox value

I am getting a problem when I try to pass a the pop_size variable equal to the value of the textbox. This variable will be used in along the script with the value of textbox. When I click on the button the value change and update the value of variable and then I reload the page and the variable is set to the value in the textbox.
<form name="myform1" action="" method="get">
Input the number of populations<br />
<input type="number" name="pop" id="pop" value=5 /><br />
<input type="button" name="b1" id="b1" value="Click to set"
onClick="setValue()" /><br />
</form>
function setValue() {
var test, test1;
test=parseInt(document.getElementById('pop').value);
pop_size = test;
}
If I'm understanding you properly, you're having a variable set that works fine until you reload, but then gets lost.
There are two basic strategies I know of for making a variable survive a page reload.
The first one I'll list seems more complicated. I'll give you the basics of it, and can tell you more if you need. Once you have the value, append it to the address of the web page within the query string. It would be something like window.location += "?pop_size=" + pop_size; but that has a lot of inherent difficulties: you'll have to have a script that checks for the query string and extracts pop_size from it, and you should replace any existing pop_size in the query string when you update it. It can work, and you can find plenty of web pages that discuss query strings and javascript, but there are easier ways.
If you're using HTML5, the much easier solution is to use sessionStorage. It's currently supported in all major browsers, but the first link I provided (to MDN) gives you a polyfill that can give you backward compatibility. It will let you store variables on the browser that will stay live until the user closes the browser window.
To save the value, MDN recommends that you do:
sessionStorage.setItem("pop_size", pop_size);
and retrieve the values on pageLoad with:
document.getElementById('pop').value = sessionStorage.getItem("pop_size") || 5; // if it's not found, default back to 5.
Honestly, I've never seen that syntax, and I'm not sure why MDN recommends it. The more standard usage of the sessionStorage object is even easier:
sessionStorage.pop_size = pop_size;
...
document.getElementById('pop').value = sessionStorage.pop_size || 5; // if it's not found, default back to 5.

Limit server populated HTML dropdown list (w/ JavaScript)

I am wanting to try to change or limit a drop down list using JavaScript, or some other solution. Unfortunately, I have no control over the way the HTML comes out that I am trying to change client side. The drop down list is generated server side, but we would like to give the user additional options to further limit the choices in the drop down list.
We can't edit what is generated, but we can insert HTML.
One suggested solution, which may not be possible, is to use JavaScript to limit the dropdown list. For example, the drop down follows the format of:
<SELECT ID="dropdown_1">
<OPTION VALUE="" >None
<OPTION VALUE="1000">AB-ITEM 1 DESCRIPTION
<OPTION VALUE="2001">AB-ITEM 2 DESCRIPTION
<OPTION VALUE="50" >AB-ITEM 8 DESCRIPTION
<OPTION VALUE="70" >BB-ITEM 3 DESCRIPTION
<OPTION VALUE="100" >BB-ITEM 5 DESCRIPTION
<OPTION VALUE="2" >ABB-ITEM 4 DESCRIPTION
</SELECT>
What I want to limit by the beginning of the text, so AB-, BB-, or ABB- in this case. The value has no rhyme or reason, it's just an index number. I don't think this is possible since this is just text, and not associated with an attribute.
One thought would be to be to:
Store the list into a JavaScript array
Keep only entries like 'TYPE-X%'
Delete original HTML list
Replace with new list stored in the Array
However, I'm not sure if this is possible, and if it is, what would be needed to create such code. Any help or references to functions or examples would be greatly appreciated.
Anything is possible (with jQuery):
$(document).ready(function() {
$("#dropdown_1 option").hide();
$("#dropdown_1 option").filter(":contains(TYPE-X)").show();
});
An advantage with this is that all of the options are still there, you just can't see them. So all it would take to return to the default list would be a call to:
$("#dropdown_1 option").show();
Edit for regex:
$(document).ready(function() {
$("#dropdown_1 option").hide();
$("#dropdown_1 option").filter(function() {
return $(this).text().match(/^AB-/);
}).show();
});
You can filter your list using a regex like seen above.
Edit: A note about jQuery, this in the filter function is the DOM element itself. In order to access the jQuery helper method text(), I first need to wrap that DOM element with the jQuery function, as edited above.
Thanks to BinaryTox1n, I was put on a good path to find an all-browser compatible solution to my question. However, it is a slightly different approach pieced together from other solutions on StackOverFlow.
The difference comes is how one deals with the OPTIONs. Though .hide() works on some browsers, it is not compatible with IE8 (and maybe some others). Alternatives and variations to .hide() also failed. Another problem with .hide() is that you also need to use .disable(). The last problem is that if you have several (20 or so) options and only 2 or 3 are visible, Chrome (and perhaps other browsers) do not render the dropdown box properly.
The best approach found is to .remove() unwanted options. No compatibility issues because the OPTION is simply removed. However, I also want to have the flexibility to add back options if needed. So the following is a version of what I'll be using:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var regex_str = "^AAB-";
var dd1 = $("#dropdown1 option");
//Clone the 'None', Current, and All options into respective variables.
//All options are stored in order to allow different selection criteria
var all_Opt = dd1.clone(true);
var none_Opt = dd1.filter(":contains(None)").clone(true);
var cur_Opt = dd1.filter(function(){
return $(this).text().match(regex_str);
}).clone(true);
//Remove all options and replace the 'None' and Current options
dd1.remove();
noneOpt.appendTo($("#dropdown1"));
curOpt.appendTo($("#dropdown1"));
});
</script>
The only thing I'd like to add is the ability for this to change using a different drop down box or some other trigger.

Special characters breaking up on onchange

I'm having a problem once again, and as you always helped me solve it, hence i'm here again.
In Joomla, we have created a website used for renting/bookings of Villa's with the portal Jomres.
Now in the backend, we can change the location of a Villa ofcourse, and this work with a dropdownbox with an onchange function.
Now here lies the problem, if we for example, click on: Cala d'Hort
Then in the inputfield(not writable) it comes as Cala d.
It breaks up everything after the apostrophe.
I've tried a bit with encoding or escaping characters, however it did not work.
The little Javascript that is behind this is:
function stext(selectid, textid) {
var select = document.getElementById(selectid);
var selectvalue = select.value;
var text = document.getElementById(textid);
text.value = selectvalue;
}
And the HTML:
<select onchange="stext('select', 'town')" id="select" class="sbox">
Is there a way that it does not break and provides the full name instead of breaking it down?
Thank you in advance!
Jeroen
This jsfiddle describes both a working and a non-working example using the JavaScript you provided. The HTML is as follows:
<select id="test1" onchange="stext('test1', 'test2')">
<option value="Cala d'Hort">Cala d'Hort</option>
<option value='Cala d'Hort'>Cala d'Hort</option>
</select>
<input id="test2" type="text" disabled />
My guess is that you have incorrectly nested quotes in your option tags.
Try seeing how the options of the select box are being populated (if they are being inserted with double-quotes). This should work if that is the case. Try using the console or alert to see which value is being fetched as your "selectValue". If that value is already wrong, that means the options from the select box is being already wrongly populated. Maybe you can provide a jsfiddle of your example and we can look at it more further.

Show Input Box on Check

You can see in the paper form attached what I need to convert into a web form. I want it to show the check boxes and disable the input fields unless the user checks the box next to it. I've seen ways of doing this with one or two elements, but I want to do it with about 20-30 check/input pairs, and don't want to repeat the same code that many times. I'm just not experienced enough to figure this out on my own. Anyone know anywhere that explains how to do this? Thanks!
P.S. Eventually this data is all going to be sent through an email with PHP.
I don't think this is a good idea at all.
Think of the users. First they have to click to enter a value. So they always need to change their hand from mouse to keyboard. This is not very usable.
Why not just give the text-fields? When sending with email you could just leave out the empty values.
in your HTML :
//this will be the structure of each checkbox and input element.
<input type="checkbox" value="Public Relations" name="skills" /><input type="text" class="hidden"/> Public Relations <br/>
in your CSS:
.hidden{
display:none;
}
.shown{
display:block;
}
in your jQuery:
$('input[type=checkbox]').on('click', function () {
// our variable is defined as, "this.checked" - our value to test, first param "shown" returns if true, second param "hidden" returns if false
var inputDisplay = this.checked ? 'shown' : 'hidden';
//from here, we just need to find our next input in the DOM.
// it will always be the next element based on our HTML structure
//change the 'display' by using our inputDisplay variable as defined above
$(this).next('input').attr('class', inputDisplay );
});
Have fun.
Since your stated goal is to reduce typing repetitive code, the real answer to this thread is to get an IDE and the zen-coding plug in:
http://coding.smashingmagazine.com/2009/11/21/zen-coding-a-new-way-to-write-html-code/
http://vimeo.com/7405114

Categories