i have a problem in preventing duplicates from being entered, i'm generated radio buttons dynamically in 2 pages at the same time using exactly one button, i take the label from the user and generate a radio button from that label, i want to prevent the user from entering 2 identical labels, here's the script which generates radios for the 2 pages any help will be appreciated
function createRadioElement(elem, label, checked) {
var id = 'option1_' + label;
$('#after').append($('<input />', {
'type': 'radio',
'fieldset':'group',
'name': 'option1',
'id': id,
'data-role': 'controlgroup',
'data-theme':'b',
'value': '1'}));
$('#after').append('<label for="' + id + '">'+ label + '</label>').trigger('create');}
function createRadioFortSecondPage(elem, label, checked) {
var id = 'option1_' + label;
$('#Inserthere').append($('<input />', {
'type': 'radio',
'fieldset':'group',
'name': 'option1',
'id': id,
'data-role': 'controlgroup',
'data-theme':'b',
'value': '1'}));
$('#Inserthere').append('<label for="' + id + '">'+ label + '</label>').trigger('create');}
that's the function i wrote to prevent duplicates:
function checkDublicates(){
var isExist=true;
var x = document.getElementById('option').value;
var labels = [];
$('#after input[type=radio]').each(function() {
labels.push($('label[for='+$(this).attr('id')+']').text());
});
for(var i=0;i<labels.length;i++){
if(x==labels[i])
{
isExist=false;}
else{
isExist=true;}
}
return isExist;}
and that's the button action:
$('#AddButton').click(function(){
var exist=checkDublicates();
<!--var isEmpty=validate();-->
<!--if(exist==true){
<!--alert("Duplicates Are Not Allowed!");
<!--}else{
var y=document.getElementById('question').value
document.getElementById('headTitle').innerHTML=y;
if(exist==false){
alert("Duplicates Not Allowed!")
}else{
createRadioElement(this,$('#option').val(),true);
createRadioFortSecondPage(this,$('#option').val(),true);
}
});
Just use $.inArray(val, arr) it will work ! http://api.jquery.com/jQuery.inArray/
But just a comment concerning your code.
Replace
document.getElementById('question').value
by
$('#question').val()
and
document.getElementById('headTitle').innerHTML=y
by
$('#headTitle').html(y)
Will be much cleaner ;-)
You can use this handy function to push elements into an array and check for duplicates at the same time. It'll return true if it catches a duplicate.
var noDupPush = function (value, arr) {
var isDup = false;
if (!~$.inArray(value, arr)) {
arr.push(value);
} else {
isDup = true;
}
return isDup;
};
// You can use it like this
var arr = ['green'];
if (noDupPush('green', arr)){
// Dup exists
}
// Or else it will just push new value to array
You could generate an id that includes the text of the label and then very quickly check for the existence of an element containing that text. For example:
function generateLabelId( userinput ){
return 'awesomelabel_' + userinput.replace(/\W/g,'');
}
var label = document.getElementById(generateLabelId( userinput ));
var labelDoesNotExist = (label == undefined );
if (labelDoesNotExist){
// create your element here
// making sure that you add the id from generateLabelId
}
Related
I have a list of checkboxes in my kendo grid.Select all option is also there.
Problem is When i click select all then all the checkboxes selected and then unselect some checkboxes and going to save then it shows me all the checkboxes.(un checked checkboxes also shown )
My Code
$('#itemGrid').on('change', '.usedchk', function () {
var checked = $(this).is(':checked');
var grid = $('#itemGrid').data().kendoGrid;
var dataItem = grid.dataItem($(this).closest('tr'));
var selected = $('#selected').val();
var id = dataItem.itemId;
if ($('#selected').val().indexOf(id) == -1) {
if ($('#selected').val() == '') {
$('#selected').val(id);
} else {
$('#selected').val(selected + "," + id );
}
}
});
use below code on save, to get all checked checkboxes as a comma separated string
var output = $.map($('#selected:checked'), function(n, i){
return n.value;
}).join(',');
I'm attempting to add +1 (or -1) to a span and then attach the value to the an href.
This is my code:
<script>
$(function () {
var valueElement = $('#value');
function incrementValue(e) {
valueElement.text(Math.max(parseInt(valueElement.text()) + e.data.increment, 0));
calculateLink();
return false;
}
$('#plus').bind('click', { increment: 1 }, incrementValue);
$('#minus').bind('click', { increment: -1 }, incrementValue);
function calculateLink() {
var value1 = document.getElementById('value').innerText;
var value2 = document.getElementById('valueone').innerText;
var value3 = document.getElementById('valuetwo').innerText;
var url = "deskshop3.aspx?item1=" + value1.text + "&item2=" + value2.text + "&item3=" + value3.text;
var element = document.getElementById('cashierLink');
element.setAttribute("href", url)
}
});
Now, what happens is that I am capable of changing the value of "value" span by pressing plus and minus buttons, but whenever I press the href "cashierLink" it always sends the default values of "value", "valueone" and "valuetwo" that the page loaded with.
What am I doing wrong?
Thanks in advance,
Arseney
Your valueElement is getting its text changed first, but then during the calculateLink() call, you are trying to assign a url using value1.text. However, value1 does not have a .text property since it is a string and not an object. This causes an error during execution and ends up bailing out of the code early, which explains why the value element changes visually, yet your href value is incorrect.
Try doing this for your URL instead:
var url = "deskshop3.aspx?item1=" + value1 + "&item2=" + value2 + "&item3=" + value3;
I'm not sure it's the way you wanna do it, but you should try to use global variables instead of text value from an element. I made a JSFiddle to show you what it could look like, you can change it the way you want to.
DEMO
/// global variables ///
var valCount = 0;
var value1 = ['first value', 'second value', 'third value'];
var value2 = ['first 2nd value', 'second 2nd value', 'third 2nd value'];
var value3 = ['first 3rd value', 'second 3rd value', 'third 3rd value'];
////////////////////////
$('#plus').bind('click', function(){ calculateLink(); });
$('#minus').bind('click', function(){ calculateLink(true); });
function calculateLink(minus) {
if(minus){
if(valCount == 0)
valCount = (value1.length-1);
else
valCount--;
} else{
if(valCount == (value1.length-1))
valCount = 0;
else
valCount++;
}
var url = "deskshop3.aspx?item1=" + value1[valCount] +
"&item2=" + value2[valCount] +
"&item3=" + value3[valCount];
document.getElementById('cashierLink').setAttribute("href", url);
}
I have a dropbox that when selected it displays its respective fields
in first image you can see there is A person without an ID so when selected it displays
something like:
if you see I added 12
Now if i change my mind and select the other option (person with ID) one field is displayed like:
I added 9999
That is ok, but now if I change my mind again and return to other selected option the values are still there like:
I would like to clean them... How can I accomplish that?
It does not matter to fill all respective fields again, I want to reset values in that case if select
person without ID, delete the 9999, on the other hand, if i select person with Id, i want to reset the vakue 12
please take a look at my fiddle
some of the jquery code is:
//function available
function validate(id, msg) {
var obj = $('#' + id);
if(obj.val() == '0' || obj.val() == ''){
$("#" + id + "_field_box .form-error").html(msg)
return true;
}
return false;
}
$(function () {
$('#has_id').show();
$('#select_person').change(function () {
$('.persons').hide();
if ($('#select_person').val() == 'typeA') {
$("#has_id").html('');
$("<option/>").val('0').text('--Choose Type A--').appendTo("#has_id");
$("<option/>").val('person-A-withID').text('person-A-withID').appendTo("#has_id");
$("<option/>").val('person-A-withoutID').text('person-A-withoutID').appendTo("#has_id");
}
if ($('#select_person').val() == 'typeB') {
$("#has_id").html('');
$("<option/>").val('0').text('--Choose Type B--').appendTo("#has_id");
$("<option/>").val('person-B-withID').text('person-B-withID').appendTo("#has_id");
$("<option/>").val('person-B-withoutID').text('person-B-withoutID').appendTo("#has_id");
}
});
$('#has_id').change(function () {
$('.persons').hide();
$('#' + $(this).val()).show();
});
});
var validation = function(){
var err = 0;
err += validate('select_person', "select person.");
err += validate('has_id', "Select whether it has an ID or not.");
if(err == 0){
alert('continue');
}else{
alert('error');
}
};
Simply make this change:
$('#has_id').change(function () {
$('.persons input').val('');
$('.persons').hide();
$('#' + $(this).val()).show();
});
New fiddle: http://jsfiddle.net/6m27M/
This simply clears out all the values any time a change is made to the #has_id dropdown.
I want create a web application that display a list of items. Suppose I have displayed a list view (say listobject1) of 3 items. when clicked on any of them I get new list view (say listobject2) which its value is according to listobject1. When again I click one of them I get another view. Now when I click back button i want to go back to previous list view i.e. when I'm now on listobject2 and again when back button is pressed I want to show listobject1. Can anybody tell me how I can do this in JavaScript?
Edit
I'm still study about the stuff but I can't solve this problem yet. In order to clarify my problem now, here's my code:
$(document).ready(function() {
$("#result").hide();
$("input[name='indexsearch']").live("click", function() {
$("#result").show();
$("#result").empty();
loading_img();
var $textInput = $("[name='valueLiteral']").val();
$.getJSON("get_onto", {
"input" : $textInput
}, function(json) {
if(json.length > 0 ) {
var arrayPredicate = [];
var arrayObject = [];
var arraySubject = [];
$.each(json, function(index, value) {
arraySubject[index] = value.subject;
arrayPredicate[index] = value.predicate;
if(value.objectGeneral != null) {
arrayObject[index] = value.objectGeneral;
} else {
arrayObject[index] = value.objectLiteral;
}
}
);
var stmt = [];
//concat all related array into string (create triple statement)
$.each(arrayPredicate, function(k,v){
stmt[k] = "<span class='subject' id="+arraySubject[k]+">"
+ arraySubject[k] + "</span> " + " -> " + v + " : "+
//change object from text to be button form
"<button class = 'searchAgain-button' name = 'searchMore' \n\
value = " + arrayObject[k] + ">" + arrayObject[k] + "</button><br> <br>";
});
stmt = stmt.sort();
$.each(stmt, function(k,v){
$("#result").append(v);
});
} else {
var $noresult = "No Result : Please enter a query";
$("#result").append($noresult);
}
});
});
$("button").live("click", function() {
$("#result").show();
$("#result").empty();
loading_img();
var $textInput = $(this).attr("Value");
//var $textInput = "G53SQM";
$.getJSON("get_onto", {
"input" : $textInput
}, function(json) {
if(json.length > 0 ) {
var arrayPredicate = [];
var arrayObject = [];
var arraySubject = [];
$.each(json, function(index, value) {
arraySubject[index] = value.subject;
arrayPredicate[index] = value.predicate;
if(value.objectGeneral != null) {
arrayObject[index] = value.objectGeneral;
} else {
arrayObject[index] = value.objectLiteral;
}
}
);
var stmt = [];
var searchMore = "searchMore";
//concat all related array into string (create triple statement)
$.each(arrayPredicate, function(k,v){
stmt[k] = "<span class='subject' id="+arraySubject[k]+">" + arraySubject[k] + "</span> " + " -> " + v + " : "+ " <button class = 'searchAgain-button' name = " +searchMore + " value = " + arrayObject[k] + ">" + arrayObject[k] + "</button><br><br>";
});
stmt = stmt.sort();
$.each(stmt, function(k,v){
$("#result").append(v);
});
} else {
var $noresult = "No Result : Please enter a query";
$("#result").append($noresult);
}
});
});
At first, user only see one button name "valueLiteral". After user perform 1st search, the result is return in a form of JSON and eventually put in stmt[] to display, which at this state the second button was create as a clickable-result which will automatically take the value of result and do second search if user click the second button.
Now the problem is, I want to add a 3rd HTML button name "back" to make the web display the previous result in stmt[] if user click on the button.
Hope this helps in clarify the problems, I'm still doing a hard work on this stuff since I'm a newbie in JavaScript. Appreciate all helps.
This is what you want almost exactly the way you want it.
You'll have to use history.pushState to push these fake events into the history.
Alternatively, you can use location.hash to store the current object, and update the hash every time you display a new list. Then onhashchange find the hash and display the appropriate list.
See http://jsfiddle.net/cFwME/
var history=[new Array(),new Array()];
history[0].id="#back";
history[1].id="#next";
Array.prototype.last=function(){
return this[this.length-1];
}
$('#list>li:not(:first)').click(function(){
if(!history[0].length || history[0].last().html()!=$('#list').html()){
history[0].push($('#list').clone(true,true));
$(history[0].id).prop('disabled',false);
history[1].length=0;
$(history[1].id).prop('disabled',true);
}
$('#list>li:first').html('This is List '+$(this).index());
});
$('#back').click(getHistory(0));
$('#next').click(getHistory(1));
function getHistory(n){
return function(){
if(!history[n].length){return false;}
history[(n+1)%2].push($('#list').replaceWith(history[n].last()));
history[n].pop();
$(history[(n+1)%2].id).prop('disabled',false);
if(!history[n].length){$(history[n].id).prop('disabled',true);}
}
}
Check out jQuery BBQ - http://benalman.com/projects/jquery-bbq-plugin/
Dynamically creating a radio button using eg
var radioInput = document.createElement('input');
radioInput.setAttribute('type', 'radio');
radioInput.setAttribute('name', name);
works in Firefox but not in IE. Why not?
Taking a step from what Patrick suggests, using a temporary node we can get rid of the try/catch:
function createRadioElement(name, checked) {
var radioHtml = '<input type="radio" name="' + name + '"';
if ( checked ) {
radioHtml += ' checked="checked"';
}
radioHtml += '/>';
var radioFragment = document.createElement('div');
radioFragment.innerHTML = radioHtml;
return radioFragment.firstChild;
}
Based on this post and its comments:
http://cf-bill.blogspot.com/2006/03/another-ie-gotcha-dynamiclly-created.html
the following works. Apparently the problem is that you can't dynamically set the name property in IE. I also found that you can't dynamically set the checked attribute either.
function createRadioElement( name, checked ) {
var radioInput;
try {
var radioHtml = '<input type="radio" name="' + name + '"';
if ( checked ) {
radioHtml += ' checked="checked"';
}
radioHtml += '/>';
radioInput = document.createElement(radioHtml);
} catch( err ) {
radioInput = document.createElement('input');
radioInput.setAttribute('type', 'radio');
radioInput.setAttribute('name', name);
if ( checked ) {
radioInput.setAttribute('checked', 'checked');
}
}
return radioInput;
}
Here's an example of more general solution which detects IE up front and handles other attributes IE also has problems with, extracted from DOMBuilder:
var createElement = (function()
{
// Detect IE using conditional compilation
if (/*#cc_on #*//*#if (#_win32)!/*#end #*/false)
{
// Translations for attribute names which IE would otherwise choke on
var attrTranslations =
{
"class": "className",
"for": "htmlFor"
};
var setAttribute = function(element, attr, value)
{
if (attrTranslations.hasOwnProperty(attr))
{
element[attrTranslations[attr]] = value;
}
else if (attr == "style")
{
element.style.cssText = value;
}
else
{
element.setAttribute(attr, value);
}
};
return function(tagName, attributes)
{
attributes = attributes || {};
// See http://channel9.msdn.com/Wiki/InternetExplorerProgrammingBugs
if (attributes.hasOwnProperty("name") ||
attributes.hasOwnProperty("checked") ||
attributes.hasOwnProperty("multiple"))
{
var tagParts = ["<" + tagName];
if (attributes.hasOwnProperty("name"))
{
tagParts[tagParts.length] =
' name="' + attributes.name + '"';
delete attributes.name;
}
if (attributes.hasOwnProperty("checked") &&
"" + attributes.checked == "true")
{
tagParts[tagParts.length] = " checked";
delete attributes.checked;
}
if (attributes.hasOwnProperty("multiple") &&
"" + attributes.multiple == "true")
{
tagParts[tagParts.length] = " multiple";
delete attributes.multiple;
}
tagParts[tagParts.length] = ">";
var element =
document.createElement(tagParts.join(""));
}
else
{
var element = document.createElement(tagName);
}
for (var attr in attributes)
{
if (attributes.hasOwnProperty(attr))
{
setAttribute(element, attr, attributes[attr]);
}
}
return element;
};
}
// All other browsers
else
{
return function(tagName, attributes)
{
attributes = attributes || {};
var element = document.createElement(tagName);
for (var attr in attributes)
{
if (attributes.hasOwnProperty(attr))
{
element.setAttribute(attr, attributes[attr]);
}
}
return element;
};
}
})();
// Usage
var rb = createElement("input", {type: "radio", checked: true});
The full DOMBuilder version also handles event listener registration and specification of child nodes.
Personally I wouldn't create nodes myself. As you've noticed there are just too many browser specific problems. Normally I use Builder.node from script.aculo.us. Using this your code would become something like this:
Builder.node('input', {type: 'radio', name: name})
My solution:
html
head
script(type='text/javascript')
function createRadioButton()
{
var newRadioButton
= document.createElement(input(type='radio',name='radio',value='1st'));
document.body.insertBefore(newRadioButton);
}
body
input(type='button',onclick='createRadioButton();',value='Create Radio Button')
Dynamically created radio button in javascript:
<%# Page Language=”C#” AutoEventWireup=”true” CodeBehind=”RadioDemo.aspx.cs” Inherits=”JavascriptTutorial.RadioDemo” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title></title>
<script type=”text/javascript”>
/* Getting Id of Div in which radio button will be add*/
var containerDivClientId = “<%= containerDiv.ClientID %>”;
/*variable count uses for define unique Ids of radio buttons and group name*/
var count = 100;
/*This function call by button OnClientClick event and uses for create radio buttons*/
function dynamicRadioButton()
{
/* create a radio button */
var radioYes = document.createElement(“input”);
radioYes.setAttribute(“type”, “radio”);
/*Set id of new created radio button*/
radioYes.setAttribute(“id”, “radioYes” + count);
/*set unique group name for pair of Yes / No */
radioYes.setAttribute(“name”, “Boolean” + count);
/*creating label for Text to Radio button*/
var lblYes = document.createElement(“lable”);
/*create text node for label Text which display for Radio button*/
var textYes = document.createTextNode(“Yes”);
/*add text to new create lable*/
lblYes.appendChild(textYes);
/*add radio button to Div*/
containerDiv.appendChild(radioYes);
/*add label text for radio button to Div*/
containerDiv.appendChild(lblYes);
/*add space between two radio buttons*/
var space = document.createElement(“span”);
space.setAttribute(“innerHTML”, “  ”);
containerDiv.appendChild(space);
var radioNo = document.createElement(“input”);
radioNo.setAttribute(“type”, “radio”);
radioNo.setAttribute(“id”, “radioNo” + count);
radioNo.setAttribute(“name”, “Boolean” + count);
var lblNo = document.createElement(“label”);
lblNo.innerHTML = “No”;
containerDiv.appendChild(radioNo);
containerDiv.appendChild(lblNo);
/*add new line for new pair of radio buttons*/
var spaceBr= document.createElement(“br”);
containerDiv.appendChild(spaceBr);
count++;
return false;
}
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:Button ID=”btnCreate” runat=”server” Text=”Click Me” OnClientClick=”return dynamicRadioButton();” />
<div id=”containerDiv” runat=”server”></div>
</div>
</form>
</body>
</html>
(source)
for(i=0;i<=10;i++){
var selecttag1=document.createElement("input");
selecttag1.setAttribute("type", "radio");
selecttag1.setAttribute("name", "irrSelectNo"+i);
selecttag1.setAttribute("value", "N");
selecttag1.setAttribute("id","irrSelectNo"+i);
var lbl1 = document.createElement("label");
lbl1.innerHTML = "YES";
cell3Div.appendChild(lbl);
cell3Div.appendChild(selecttag1);
}
Quick reply to an older post:
The post above by Roundcrisis is fine, IF AND ONLY IF, you know the number of radio/checkbox controls that will be used before-hand. In some situations, addressed by this topic of 'dynamically creating radio buttons', the number of controls that will be needed by the user is not known. Further, I do not recommend 'skipping' the 'try-catch' error trapping, as this allows for ease of catching future browser implementations which may not comply with the current standards. Of these solutions, I recommend using the solution proposed by Patrick Wilkes in his reply to his own question.
This is repeated here in an effort to avoid confusion:
function createRadioElement( name, checked ) {
var radioInput;
try {
var radioHtml = '<input type="radio" name="' + name + '"';
if ( checked ) {
radioHtml += ' checked="checked"';
}
radioHtml += '/>';
radioInput = document.createElement(radioHtml);
} catch( err ) {
radioInput = document.createElement('input');
radioInput.setAttribute('type', 'radio');
radioInput.setAttribute('name', name);
if ( checked ) {
radioInput.setAttribute('checked', 'checked');
}
}
return radioInput;}
Patrick's answer works, or you can set the "defaultChecked" attribute too (this will work in IE for radio or checkbox elements, and won't cause errors in other browsers.
PS Full list of attributes you can't set in IE is listed here:
http://webbugtrack.blogspot.com/2007/08/bug-242-setattribute-doesnt-always-work.html
why not creating the input, set the style to dispaly: none and then change the display when necesary
this way you can also probably handle users whitout js better.
My suggestion is not to use document.Create(). Better solution is to construct actual HTML of future control and then assign it like innerHTML to some placeholder - it allows browser to render it itself which is much faster than any JS DOM manipulations.
Cheers.