How to get controls by dynamic name in javascript - javascript

I have 5 dropdown with name postfix by 1,2,3...so on... How can i get name of these dropdown in javascript
var TotalLvl=document.getElementById('<%=dd_Designation_Level.ClientID%>').value;
for (var i = 1; i <= d; i++) {
var DesLvl='Designation' +i;
if ((document.getElementById('<%=' + DesLvl +'%>').value == "0")) {
alert('Designation' + i 'should be selected');
}
}
i am not able to do this by this dynamic name DesLvl

Related

how to manage a counter on different blades in laravel?

Hello i am working on a project i need to send item in session and add limit only 4 item will be add on session. it's working on one blade but when i move to another blade it will show nothing on the button like how many items in the session and when am trying to add another item it will add.
this is my script
var increment = 0;
$(document).ready(function(){
$(".compare").click(function(){
increment++;
document.getElementById('compare').innerHTML = "";
document.getElementById('compare').innerHTML = "Compare (" +increment+")";
if(increment == 4)
{
var array = document.getElementsByClassName('compare');
for (var i = 0 ; i < array.length ; i++)
{
array[i].setAttribute('disabled','');
}
}
i am wanted to add only 4 items in the session from every where.
please send any solution .
Try this :
var increment = 1;
$(document).ready(function(){
if(localStorage.getItem("compare") > 0){
increment = localStorage.getItem("compare");
document.getElementById('compare').innerHTML = "Compare (" +increment+")";
} else {
document.getElementById('compare').innerHTML = "";
}
$(".compare").click(function(){
if(increment == 4)
{
var array = document.getElementsByClassName('compare');
for (var i = 0 ; i < array.length ; i++)
{
array[i].setAttribute('disabled','');
}
} else {
increment++;
localStorage.setItem("compare", increment);
document.getElementById('compare').innerHTML = "Compare (" +increment+")";
}
}
}

Not able add multiple option to select

function successCallback(caRecords) {
var x = document.getElementById("custAccount"); // select
var option1 = document.createElement("option"); //options
//var accno = 0;
// caRecords i am fetch from MS CRM
var count = caRecords[0].results.length;
if (caRecords != null && count > 0) {
alert("records are not null");
for (var i = 0 ; i < count; i++)
{
var text = caRecords[0].results[i].new_name;
// alert(text + "J=" + j);
option1.text = text;
option1.value = j;
x.add(option1);
j++;
}
}
I got six records and try to insert that values into select as option. It showing last value of my 6 values.
Can anyone help me to improve my code?
You can iterate your values like this...
function successCallback(caRecords) {
var x = document.getElementById("custAccount"); // select
var options = "";
var count = caRecords[0].results.length;
if (caRecords != null && count > 0) {
alert("records are not null");
for (var i = 0; i < count; i++) {
options += "<option value=" + j + ">" + caRecords[0].results[i].new_name + "</option>";
j++;
}
x.innerHTML = options;
}

Verify Alphabet Textbox only

How to Verify my text boxes? This is a JSP page created to take in information.
First name should no have Numbers in there, I can enter the name as "103249" and the text box takes it. Also, How do I fix the last name as well?
var btn = "";
function validate(myform) {
if (btn == "submit") {
//Validate Form only on 'submit' button (not for 'clear' button)
var num = 0;
var message = "";
if(myform.firstname.value == "") {
message += "- First Name must be completed \n";
num = 1;
}
if(myform.lastname.value == "") {
message += "- Last Name must be completed \n";
num = 1;
}
if(myform.dateofbirth.value == "") {
message += "- Date of Birth must be completed \n";
num = 1;
}
//RADIO BUTTON VALIDATION
var g = "";
//Loop thru each radio button, verify if "checked"
for (var i=0; i<myform.gender.length; i++) {
if (myform.gender[i].checked) {
//Changes value of "g" if a value is selected
g = myform.gender[i].value;
}
}
//If no radio button selected, "g" will still = ""
if (g == "") {
message += "- Gender must be completed \n";
num = 1;
}
if(myform.gpa.value == "") {
message += "- GPA must be completed \n";
num = 1;
}
//Dropdown
if(myform.education.value == "") {
message += "- Education must be completed \n";
num = 1;
}
//Dropdown
if(myform.job.value == "") {
message += "- Occupation must be completed \n";
num = 1;
}
//RADIO BUTTON VALIDATION
var g = "";
//Loop thru each radio button, verify if "checked"
for (var i=0; i<myform.married.length; i++) {
if (myform.married[i].checked) {
//Changes value of "g" if a value is selected
g = myform.married[i].value;
}
}
//If no radio button selected, "g" will still = ""
if (g == "") {
message += "- Married must be completed \n";
num = 1;
}
//if(myform.spouse.value == "") {
//message += "- Spouse must be completed \n";
//num = 1;
//}
//RADIO BUTTON VALIDATION
var g = "";
//Loop thru each radio button, verify if "checked"
for (var i=0; i<myform.children.length; i++) {
if (myform.children[i].checked) {
//Changes value of "g" if a value is selected
g = myform.children[i].value;
}
}
//If no radio button selected, "g" will still = ""
if (g == "") {
message += "- Children must be completed \n";
num = 1;
}
//Dropdown
//Only require if previous field Children marked "Yes"
if(myform.numchild.value == "0" && g == "Yes") {
message += "- Number of Children must be completed \n";
num = 1;
}
if(myform.childSupport.value == "") {
message += "- Child Support must be completed \n";
num = 1;
}
if(myform.creditScore.value == "") {
message += "- Credit Score must be completed \n";
num = 1;
}
if (num == 1) {
alert ("Please complete or correct the following required fields: \n\n"+message);
return false;
} else {
return true;
} //end if
} //end if submit button
if (btn == "delete") {
//Confirm if want to delete
var result = confirm("Are you sure you want to permanently delete this survey?");
return result;
} //end if delete button
} //end func
//=============== TO DISABLE CCARDS AND NUMBER OF CHILDREN DROPBOXES ==================
function handleSelect(myRadio){
if(myRadio.value == "No"){
document.getElementById("cc_use").selectedIndex = 0; //reset to initial default value
document.getElementById("cc_use").disabled = true;
} else {
document.getElementById("cc_use").disabled = false;
} //end if
} //end func
function handleSelect1(myRadio1){
if(myRadio1.value == "No"){
document.getElementById("numchild").selectedIndex = 0; //reset to initial default value
document.getElementById("numchild").disabled = true;
} else {
document.getElementById("numchild").disabled = false;
} //end if
} //end func
//=============== POPULATE OCCUPATION DROPDOWN BASED ON INDUSTRY DROPDOWN SELECTION ==================
function configureDropDownList(industry, occupation) { //params: id's of sending dropdown & dropdown to change
//Categories: Create a String value of all the list items in the Java ArrayList of Categories
//It translates into a String with opening and closing brackets: [], need to delete brackets from String
var categoryListString = "<%= lstCategories %>";
categoryListString = categoryListString.replace("[","");
categoryListString = categoryListString.replace("]","");
//Split the Category String into a new Javascript array of Categories
var categoryArray = new Array();
categoryArray = categoryListString.split(", "); //Make sure it's comma + space
//Occupations: Create a String value of all the nested list items in the Java ArrayList of ArrayLists: all occup names for each category
//It translates into a String with opening and closing DOUBLE brackets: [[]], need to delete brackets from String
var occupByCatsString = "<%= loccp %>";
occupByCatsString = occupByCatsString.replace("[[","");
occupByCatsString = occupByCatsString.replace("]]","");
//Split the String into a new Javascript array
var occupationsArray = new Array();
occupationsArray = occupByCatsString.split("], [");
//Loop thru array and break into further individual nested arrays for occup names in each category
for (var i = 0; i < occupationsArray.length; i++) {
occupationsArray[i] = occupationsArray[i].split(", "); //Make sure it's comma + space
}
//alert("new occup name array index 0: "+occupationsArray[0]+", index 1: "+occupationsArray[1]);
//alert("Individ occup names in index 0, name 0: "+occupationsArray[0][0]+", name 1: "+occupationsArray[0][1]);
//Categories array (categoryArray) & Nested Occup Names Array by Category (occupationsArray)
//are parallel arrays in order to match Category names with appropriate group of Occup Names
//Loop thru list of all Categories to find selected one
//and create dropdown list of matching Occup Names for that Category
for (var i = 0; i < categoryArray.length; i++)
{
if (industry.value == categoryArray[i]) {
//Call method to create Occupation dropdown list values
//Send array of that Category's list of Occupation Names as parameter, and 'occupation' id value of select
createOccupationItems(occupationsArray[i], occupation);
}
} //end for
} //end function
function createOccupationItems(occupArr, occupation) {
//Parameters in: array of that Category's list of Occupation Names, and 'occupation' id value of select
document.getElementById(occupation).options.length = 0;
for (var i = 0; i < occupArr.length; i++) {
createOption(document.getElementById(occupation), occupArr[i], occupArr[i]);
}
} //end function
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
} //end function
</script>
Here is the actual code to validate:
<div class="sameLine">
<label for="firstname">First Name:</label>
<input type="text" name="firstname" value="<%=surv.getFname()%>">
</div>
<div class="sameLine">
<label for="lastname">Last Name:</label>
<input type="text" name="lastname" value="<%=surv.getLname()%>">
EDIT: Here is the code that I found to verify the letters. It does not work, ignoring it if anything:
if(myform.firstname.value.search(/[^a-zA-Z]+/) === -1) {
message += "- First Name must have letters only \n";
num = 1;
}

How to detect 2nd appearance of character?

I am trying to add a toolbox to a MediaWiki Chat using JavaScript. Well, with this code I do a AJAX request to another MediaWiki page (MediaWiki:Chat-herramientas-2) to get the content of the toolbox and, on the chat, print it.
The format of the toolbox content is:
- Navigation
* Page 1
* Page 2
* Page 3|Hahaha
* #|Execute script|hello()
The first line is the first < li > of the < ul > (toolbox). It has the class "active".
The second and third lines are "< a >" with href "#", and the text are "Page 1" and "Page 2", respectly.
The fourth line has a href with url ".../Page 3" and the text is "Hahaha".
But with the fifth line, I want to insert a blank href ("#"), with the text "Execute script" and after the 2nd "|" add the onclick attribute with "hello()" on it.
I can't accomplish it because I don't know how to detect the 2nd appearance of a character. The full code is this:
$(function() {
var $chatheader = $('#ChatHeader');
select = 'MediaWiki:Chat-herramientas-2';
var $menu = $('<ul class="dropdown"></ul>')
.insertAfter($chatheader)
function flatten (options, indent) {
var flattened = [];
indent = indent || '';
for (var i = 0; i < options.length; i++) {
if ($.isArray(options[i])) {
flattened = flattened.concat(flatten(options[i], '* '));
} else {
flattened.push(indent + options[i]);
}
}
return flattened;
}
function render (lines) {
var options = '', selected = ' selected',
ignore = { '(': 1, ':': 1, '<': 1 };
for (var i = 0; i < lines.length; i++, selected = '') {
if (!lines[i].length || ignore[lines[i][0]]) {
continue;
}
var contents = mw.html.escape( lines[i].substring(2) );
if (lines[i].substring(0, 2) === '* ') {
var clase = contents.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-').toLowerCase();
var url = contents.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-').toLowerCase();
var checksitiene = /\|/g.test(contents)
if(checksitiene) {
var wachem = contents.replace(/\|/,'">');
options += '<li class="' + clase + '"' +
selected + '><a target="_blank" href="/wiki/' + wachem + '</a></li>';
} else {
options += '<li class="' + clase + '"' +
selected + '>' + contents + '</li>';
}
} else {
options += '<li class="active">' + contents + ' <span>▼</span></li>';
}
}
$menu.append(options);
}
if (typeof select === 'string') {
$.get('/wiki/' + select + '?action=raw&ctype=text/javascript')
.done(function (data) {
render(data.split(/\r\n|\n|\r/));
});
} else if ($.isArray(select)) {
render(flatten(select));
}
});
String.prototype.indexOf accepts two arguments, the first is the string you want to match, and the second is the index from which to start your match. See MDN.
Thus, after using indexOf to find the first instance of a string, you can then search from that index+(length of the matching string) to find the next match.
A function that can be called multiple times to receive the next index in a string:
function makeIndexer(text,pattern,start){
start = start||0;
var patternLength = pattern.length
, initialStart = start
;
return function(){
var index = text.indexOf(pattern,start);
if(index === -1){ //start over from initial start index after we reach the end
start = initialStart;
}else{
start = index + patternLength;
}
return index;
}
}
Then use it like this:
var nextIndex = makeIndexer("Wow, what an awesome function!","w")
nextIndex() //2 still case sensitive like indexOf
nextIndex() //5
nextIndex() //14
nextIndex() //-1 Like indexOf, returns -1 when there are no more matches
nextIndex() //2 starting over

Get the value from only selected checkbox

I am trying to get the value from a checkbox using javascript.
I want only one checkbox value to be passed to the javascript function, and if multiple are selected, an alert box informing that only one box can be checked for the function.
I've tried this:
var publish_trigger = document.querySelector("#publish_trigger");
publish_trigger.onclick = function() {
var _posts = document.getElementsByName('post_id[]');
var check = _posts.checked;
var boxes = _posts.length;
var txt = "";
if(check.length > 1) {
alert("Only one at a time");
} else {
for (i = 0; i < boxes; i++) {
if (_posts[i].checked) {
txt = txt + _posts[i].value + " "
}
}
}
alert(txt);
return false;
}
This code is wrong:
var _posts = document.getElementsByName('post_id[]');
var check = _posts.checked;
getElementsByName() returns a NodeList (effectively an array) of elements, so your variable _posts doesn't have a checked property. You need to loop through _posts to count the checked property on the individual elements within _posts.
You already have a for loop so add the validation in there:
var count = 0;
for (var i = 0; i < boxes; i++) {
if (_posts[i].checked) {
if (++count > 1) {
alert("Only one checkbox may be checked at a time.");
return false;
}
// I don't know what you're trying to do with the following line
// but I've left it in.
txt = txt + _posts[i].value + " "
}
}
(Note: unrelated to your question, you should declare the loop counter i within your function otherwise it will be global and might lead to hard to debug problems if you are using it in other places too.)

Categories