Special characters breaking up on onchange - javascript

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.

Related

Combining javascript and jquery to fill multiple hidden fields - bad idea?

I'm trying to find the best way to make my teachers' lives a little easier.
I've got a select field and list of options generated by a tlist sql query. The select field itself already has a javascript attached to it, which fleshes out other field values (credit values and credit types) elsewhere based on the id of the select option chosen. This is the javascript that works for that purpose:
<script type="text/javascript">
function changeValue(){
var option=document.getElementById('courseno').value;
if(option=="E100"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngFresh";
}
else if(option=="E200"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngSoph";
}
}
</script>
I also need to populate a hidden field that is (and must remain) outside the tlist sql tag that generates the select list.
Here is my sql code:
<select id="courseno" name="course_number" onchange="changeValue();">
<option value="">Select a Course</option>
~[tlist_sql;
SELECT cc.course_number, cc.section_number, c.COURSE_NAME
FROM cc cc
RIGHT JOIN COURSES c ON c.COURSE_NUMBER = cc.course_number
RIGHT JOIN STUDENTS s ON cc.studentid = s.id
WHERE cc.studentid = ~(curstudid)
AND TERMID = ~(curtermid)
AND c.CreditType LIKE 'English%'
AND NOT EXISTS (
SELECT * FROM storedgrades sg
WHERE sg.studentid = ~(curstudid)
AND sg.course_number = c.course_number
)
ORDER BY c.course_name;]
<option name="~(course_no)" value="~(course_no)" id="~(secno)">~(course_no).~(secno) (~(cname))</option>
[/tlist_sql]
</select></td>
</tr>
And just below that is the hidden field I would like to populate:
<td width="25%" class="bold"> </td>
<td><input type="text" id="secnum" name="section_number" value=""> </td>
I gave each of the options the section number as its ID, thinking I could use the ID element of each of those options and some clever jquery to populate the hidden field, but I'm having no luck. I just read on another question that was ably answered by the community that you shouldn't use an option ID tag that begins with a number... so now what can I do?
Could somebody please help me?
Thanks forever,
Schelly
I don't think your problem comes from the ID being a number. We haven't seen what jQuery you've tried, but you most likely don't need jQuery at all. Assuming what you have is working correctly, and the PowerSchool code is putting out elements the way you expect them to be (View Source in your browser to be sure, if this doesn't work), you should be able to grab the ID from the selected option inside your changeValue function, store it in a variable, and push that value into the "secnum" field as follows:
function changeValue(){
var courseDropdown = document.getElementById('courseno');
var selectedElement=courseDropdown.options[courseDropdown.selectedIndex];
var option=selectedElement.value;
var courseNo = selectedElement.getAttribute("id");
if(option=="E100"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngFresh";
}
else if(option=="E200"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngSoph";
}
document.getElementById('secnum').value=courseNo;
}
I changed the way that your "option" variable is being set, but it will work the same way. You might end up wanting to move the last line, where the "secnum" field is being set, or wrap it in an "if", etc.; I don't know your full requirements.
All that said, there would be nothing wrong with using jQuery in this situation, but it's not necessary in this case unless you need extreme backwards-browser compatibility.
Working Example Here
You can use multiple on change events to do whatever you want. On change add a new event and populate the hidden input. You can define custom attributes to any html element with any data that is required to populate the hidden input
<select id="myselect">
<option>Select</option>
<option data-number="1">One</option>
<option data-number="2">Two</option>
<option data-number="3">Three</option>
<option data-number="4">Four</option>
<option data-number="5">Five</option>
</select>
<input type="hidden" id="hiddenInput"/>
$(document).ready(function(){
$('#myselect').on('change', mySelectChange);
function mySelectChange(){
console.log('your standard change value here');
}
$('#myselect').on('change', mySelectChange2);
function mySelectChange2(){
var option = $("#myselect option:selected");
console.log(option.text());
console.log(option.attr('data-number'));
}});

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.

$('select option:selected').text() and Attr.specified is deprecated warning

In my project I need to update a backbone model with both the selected value and text from a <select>.
For this purpose I am calling
model.set 'value', $('select').val()
model.set 'value_text', $('select option:selected').text()
(I am using coffee script as well). Because of some problem in jQuery v2.0.3 which I am currently using I am receiving this warning:
Attr.specified is deprecated. Its value is always true.
I know there were questions on SO about this warning, but I want to ask something completely different:
Since updating to a newer version of jQuery (where the problem might be fixed) is not possible in next few months I would like to ask whether there is other way round to receive the selected option's text instead of that used above. I am not against pure JS solution if there is no other using jQuery.
Any help is highly appreciated.
EDIT for #KevinB: The warning is caused by asking whether there is selected attribute on that option.
To *fix* it without changing anything else, you can just use .filter.
$('select option').filter(function (i) { return this.selected; }).text();
I prefer do that in a different approach. See the code.
Inside view.
events:
"change input":"updateModel"
"change select" : "SelectedItem" //Just for example.
selectedItem:(element)->
selectedOption = element.target.selectedOptions
alert **selectedOption.item().value** // the value of the selected item. now you can set it on model.
updateModel:(element)->
#model.setNew(element.target.name, element.target.value)
Inside model.
setNew:(newName, newValue)->
#set newName, newValue
Html file.
<select>
<option value="renan">Renan</option>
<option value="carvalho">Carvalho</option>
</select>
<input type="text" name="customer" />
Hope it helps.

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.

javascript cannot call an element in array

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.

Categories