How to get radio button selected value from dynamically generated radio buttons? - javascript

Hi I am developing web application in angularjs. I am generating radiobuttons dynamically using ng-repeat as below.
<ul>
<li ng-repeat="level in permissions">
<input name="level.perm_levelname" type="radio" ng-model="level.perm_levelname" value="{{level.perm_levelname}}"> {{level.perm_levelname}}
<a ng-click="gotopermMap({permisssionID: level.id})">View</a>
</li>
</ul>
<input type="button" value="APPLY" ng-click="apply()" />
I am trying to get selected radio button as below.
$scope.apply=function()
{
var permname = $scope.name;
console.log($scope.level.perm_levelname);
}
I am getting error Cannot read property 'perm_levelname' of undefined. May i get help here to get selected radio button? Thank you

group radio buttons by a name and specify a common scope variable for radio buttons ng-modal
<ul>
<li ng-repeat="level in permissions">
<input name="myradiobtn" type="radio" ng-model="myradioBtnValue" ng-value="level.perm_levelname">
{{level.perm_levelname}}
<a ng-click="gotopermMap({permisssionID: level.id})">View</a>
</li>
</ul>
<input type="button" value="APPLY" ng-click="apply()"/>

Use ng-click event for radio button to get current selected value and assign the value a scope object. then get the value from saved scope abject while you click apply button.
DEMO:
function TodoCtrl($scope) {
$scope.permissions= [{perm_levelname:"hai"},{perm_levelname:"bye"},{perm_levelname:"come"},{perm_levelname:"go"}]
$scope.apply=function()
{
alert($scope.currecntClickValue);
}
$scope.currecntClick=function(currecntClickValue)
{
$scope.currecntClickValue=currecntClickValue.perm_levelname;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<h2>Todo</h2>
<div ng-controller="TodoCtrl">
<ul>
<li ng-repeat="level in permissions">
<input name="groupName" type="radio" ng-click="currecntClick(level)" ng-value="level.perm_levelname">
{{level.perm_levelname}}
View
</li>
</ul>
<input type="button" value="APPLY" ng-click="apply()"/>
</div>
</div>

you should use radio button group like this--
<ul>
<li ng-repeat="level in permissions">
<input name="btnGroup" type="radio" ng-model="radioButtonValue" value="{{level.perm_levelname}}">
{{level.perm_levelname}}
<a ng-click="gotopermMap({permisssionID: level.id})">View</a>
</li>
</ul>
<input type="button" value="APPLY" ng-click="apply()"/>
And inside of Controller-
$scope.radioButtonValue='';
$scope.apply=function()
{
var permname = $scope.name;
console.log($scope.radioButtonValue);
}

Related

check the radio button when click on the li using javascript

I have radio button
Html code:
<input type="radio" class="first" name="bright" checked>
<input type="radio" class="second" name="bright" >
<input type="radio" class="third" name="bright">
<input type="radio" class="four" name="bright">
And i have a nav bar
Html code
<ul class="nav">
<li class="st st1 active" data-cont="first">
<h2 class="inner">وزارة الاستثمار</h2>
</li>
<li class="st st2" data-cont="second">
<h2 class="inner">وزارة التجارة</h2>
</li>
<li class="st st3" data-cont="third">
<h2 class="inner">جهات حكومية اخرى</h2>
</li>
<li class="st st4" data-cont="four">
<h2 class="inner">مكتب هندسي</h2>
</li>
</ul>
These 2 are conected with the data-cont that have the class of the radio button
I want when i click on the li the correct radio button be checked using javascript
I tried to make it using this code in JavaScript
let radio = document.querySelectorAll("input");
let radioArray = Array.from(radio);
let tabs = document.querySelectorAll(".nav li");
let tabsArray = Array.from(tabs);
tabsArray.forEach((ele) => {
ele.addEventListener("click", function (e) {
tabsArray.forEach((ele) => {
ele.classList.remove("active");
});
e.currentTarget.classList.add("active");
document.querySelector(e.currentTarget.dataset.cont).checked = true;
});
});
I try to remove the active class from li and put it on the li where i click then i want the radio button be checked
Any body can help me on this?
the last querySelector is where your code is failing you're not referencing the class for your input it needs to be document.querySelector('.' + e.currentTarget.dataset.cont).checked = true; note the "." prefix
Although that answers your question there is probably more value in pointing out that by changing your html markup to be a little more accessible you can eliminate the need for all of the javascript in your example
e.g.
input:checked + label {
color:Red;
}
<div><input type="radio" id="first" name="bright" checked>
<label for='first'>وزارة الاستثما</label>
</div>
<div>
<input type="radio" id="second" name="bright" >
<label for='second'>وزارة التجارة</label>
</div>
<div>
<input type="radio" id="third" name="bright">
<label for='third'>جهات حكومية اخرى</label>
</div>
<div>
<input type="radio" id="four" name="bright">
<label for='four'>مكتب هندسي</label>
</div>
The use of labels associated with your radio buttons is now significantly more accessible and you can drastically reduce a lot of your markup ( though to be accessible you would need to provide a more meaningful name for for attribute.

ng-checked in radio button

I'm making a quiz app.To show the progress of the quiz there is question pallette of small boxes which turn yellow when users click on any of the the radio button to show that the user has attempted the question.Along with this there is a button to move to the previous question.To show the users initial answer I have used ng-checked directive with some logic in the controller.Everything is working fine but after attempting a question when I move to the next question and click on the same option as the previous question then the question pallette box does not turn yellow.But when I click on the other option it works fine.
.html
<div class="questionsBox" >
<div class="questions">{{liveCtrl.questions[liveCtrl.activeQuestion].question}}</div>
<ul class="answerList">
<li>
<label>
<input data-id="{{liveCtrl.activeQuestion}}" type="radio" ng-checked="liveCtrl.useranswers[liveCtrl.activeQuestion].q===1" ng-click="liveCtrl.answers(liveCtrl.activeQuestion,1)" name="answerGroup" value="0" > {{liveCtrl.questions[liveCtrl.activeQuestion].optionA}}</label>
</li>
<li>
<label>
<input data-id="{{liveCtrl.activeQuestion}}" type="radio" ng-checked="liveCtrl.useranswers[liveCtrl.activeQuestion].q===2" ng-click="liveCtrl.answers(liveCtrl.activeQuestion,2)" name="answerGroup" value="1" > {{liveCtrl.questions[liveCtrl.activeQuestion].optionB}}</label>
</li>
<li>
<label>
<input data-id="{{liveCtrl.activeQuestion}}" type="radio" ng-checked="liveCtrl.useranswers[liveCtrl.activeQuestion].q===3" ng-click="liveCtrl.answers(liveCtrl.activeQuestion,3)" name="answerGroup" value="2" > {{liveCtrl.questions[liveCtrl.activeQuestion].optionC}}</label>
</li>
<li>
<label>
<input data-id="{{liveCtrl.activeQuestion}}" type="radio" ng-checked="liveCtrl.useranswers[liveCtrl.activeQuestion].q===4" ng-click="liveCtrl.answers(liveCtrl.activeQuestion,4)" name="answerGroup" value="3" > {{liveCtrl.questions[liveCtrl.activeQuestion].optionD}}</label>
</li>
</ul>
<div class="questionsRow">
<button ng-disabled="liveCtrl.questions.length==liveCtrl.activeQuestion+1" class="subques btn btn-lg btn-secondary" ng-click="liveCtrl.nextQuestion()">Save & Next</button>
<button ng-click="liveCtrl.prevQuestion()" ng-disabled="liveCtrl.activeQuestion == 0" class="subques btn btn-lg btn-secondary" >Previous</button>
</div>
</div>
//Question Pallete
<div class="question-pallete">
<div id="{{$index}}" ng-repeat="question in liveCtrl.questions" class="square">
<a ng-click="liveCtrl.gotoQues($index)">
{{$index + 1}}
</a>
</div>
//jquery to give color to the boxes
<script type="text/javascript">
$(document).on('click',"input[name='answerGroup']",function(){
var qid=$(this).data('id');
console.log(qid);
$('#'+qid).addClass('box-color');
});
</script>
Controller functions
this.nextQuestion=()=>{
live.activeQuestion++;
//console.log(live.activeQuestion);
};
this.prevQuestion=()=>{
live.activeQuestion--;
//console.log(live.activeQuestion);
};
this.gotoQues=(qno)=>{
live.activeQuestion=qno;
}
this.answers=(qid,option)=>{
//console.log(qid);
live.useranswers[qid]={
q:option
};
When I'm tried to console qid in jquery part it outputs the same qid for the same option in the next question but it is not the case for other options.I think "data-id" in html is not updating for that case.Sorry If I was not able to explain it properly.
I find 2 issues with your implementation.
I don't see ng-model in any of your input field.
Why don't you use ng-class instead of using jquery to get the id and add class?
<label ng-class="val==0 ? 'highlight':''">
<input type="Radio" ng-model="val" ng-value="0">Option A</label>
Here is the jsfiddle link

Iterating array of object in angular ng-repeat

I have an object like this
var questions= [{ QuestionId:"1",
QuestionName:"loreum ispum?",
Answers: [{option:"A",Score:10},
{option:"B",Score:10}
]
},
{ QuestionId:"2",
QuestionName:"loreum ispum?",
Answers: [{option:"A",Score:10},
{option:"B",Score:10}
]
}]
Iterating through ng-repeat
<ul ng-repeat="question in vm.questions">
<div class="">{{question.QuestionName}}</div>
<input type="text" ng-model="getdetails.QuestionId" ng-value="question.QuestionId" style="display:none"/>
<li ng-repeat="answer in question.Answers track by $index">
<input type="radio" name="questionId_[$index]">" ng-model="getdetails.Score" ng-value="answer.Score" />
</li>
<button class="btn btn-success no-broder-radius" ng-click="change(getdetails)">Submit</button>
</ul>
and clicking on submit button I need to get the Question id and selected input value.
Controller :
$scope.getdetails={};
$scope.change=function(getDetails) {
// I am getting only input radio value not getting question id
}
I am getting only input radio value not getting question id
If getDetails is a $scope variable then you can directly access it in your controller, you don't need to pass it from view.
Try this:
<ul ng-repeat="question in vm.questions">
<div class="">{{question.QuestionName}}</div>
<input type="text" ng-model="getDetails.QuestionId" ng-value="question.QuestionId" style="display:none"></input>
<li ng-repeat="answer in question.Answers track by $index">
<input type="radio" name="questionId_[$index]">" ng-model="getdetails.Score" ng-value="answer.Score" />
</li>
<button class="btn btn-success no-broder-radius" ng-click="change(question)">Submit</button>
</ul>
Now in change function, you will have access to the full object.

if checkbox is checked remove class from div on click

Posted a question on about the same project in the morning. After battling it for a while came up with a bit different approach.
Trying to build a filter. And the idea is that a filter checkboxes have matching id's with filtered items classes. So, once a filter item clicked, filtration is applied to item class. Classes (except for inditem) and ids are dynamic
simplified html of it
<div class="itemswrap">
<div class="inditem dynamic1"></div>
<div class="inditem dynamic2"></div>
<div class="inditem dynamic3"></div>
<div class="inditem dynamic2"></div>
</div>
<ul class="subnav">
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="dynamic1" />
<label for="dynamic1">whatever label</label>
</li>
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="dynamic2" />
<label for="dynamic1">whatever label</label>
</li>
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="dynamic3" />
<label for="dynamic1">whatever label</label>
</li>
</ul>
js
$(".lifilter").each(function() {
var filter1 = $(this).find('.filtercheck').attr('id');
if ( $(this).find('.filtercheck').attr('checked') ) {
$(this).find('.filtercheck').click(function(){
$('.' + filter1).removeClass('checkeditem').hide();
});
}
else
{
$(this).find('.filtercheck').click(function(){
$('.inditem').hide();
$('.' + filter1).addClass('checkeditem');
});
}
});
and this one marked as important not to be hidden when extra items are added into filtration
.checkeditem {display:block !important}
Initial filtration works fine. But when I click on checked item the associated div does not hide.
Do you mean something like
var $filters = $('.filtercheck').change(function() {
var $items = $('.inditem').hide();
var filters = $filters.filter(':checked').map(function() {
return '.' + this.id;
}).get();
if (filters.length) {
$items.filter(filters.join()).show();
} else {
$items.show();
}
});
.checkeditem {
display: block !important
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="itemswrap">
<div class="inditem dynamic1">dynamic1</div>
<div class="inditem dynamic2">dynamic2</div>
<div class="inditem dynamic3">dynamic3</div>
<div class="inditem dynamic2">dynamic2</div>
</div>
<ul class="subnav">
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="dynamic1" />
<label for="dynamic1">whatever label</label>
</li>
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="dynamic2" />
<label for="dynamic1">whatever label</label>
</li>
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="dynamic3" />
<label for="dynamic1">whatever label</label>
</li>
</ul>
The problem with the code is that the event handler attaches the second click event on the first successful case. This means that the "click" on the checkbox is being given the "addclass" case, and all subsequent clicks are being handled by that handler instead of the intended one.
Using the same HTML. I created this:
$(document).ready(function() {
$(".filtercheck").click(function(){
$('.inditem').hide();
var filter1 = $(this).attr('id');
$('.' + filter1).toggleClass('checkeditem');
});
});
which I think is the intended behavior? Instead of individually attaching click handlers, I simply attached a single handler to all of them. It would be fairly easy to do something like
$(this).prop()
to determine if the currently clicked on item had was active or not. For this simple example, I opted to just use a class toggle to illustrate the point.

Submit filter form on link click

I'm trying to make something a bit like this:
This is my code: http://jsfiddle.net/928Dj/19/
$("ul.opt").addClass("hidden");
$('#filter > li > a').on("click", function (e) {
var cache = $(this).next('ul');
$('#filter ul:visible').not(cache).hide();
cache.toggle();
});
I'm trying to make it degradable so without javascript they can submit the form to adjust the results, but with javascript they can just click the text of the desired result.
Question A
How can I make it so by them clicking the text alone, with javascript enabled, it not only selects the radio button but also submit the form.
Question B
Is my code the right approach to achieve this desired outcome?
Replace the radio buttons with submit buttons.
<input type="submit" name="status" value="Status 1">
i think google uses <a> tag instead <input> and (but i'm not sure) catches the click and makes a ajax call to update only the result (without any form)... like: http://jsfiddle.net/928Dj/25/
HTML, change <input> in <a>:
Status 1
JS
$('ul.opt a').click(function(e){
e.preventDefault();
$(this).parents(".opt").find("a").removeClass("active");
$(this).addClass("active");
$.get($(this).attr("href"),function(res){
//do something with response
});
});
On <a> click the JS simply perform search.action (or other search service) with sortDate=status1 like parameter via AJAX, for sort the result.
You can concat the sorting parameters status=status1&date=date1 for multiple sorting.
I don't know if there are any ways to perform the submit without using javascript (and without reload all page).
I've updated your fiddle with submit buttons that are hidden if javascript is enabled.
<div>
<form action="/echo/html/">
<ul id="filter">
<li> Any status ▾
<ul class="opt">
<li>
<label>
<input type="radio" name="status" />Status 1</label>
</li>
<li>
<label>
<input type="radio" name="status" />Status 2</label>
</li>
<li>
<input type="submit" value="submit"/>
</li>
</ul>
</li>
<li> Any date ▾
<ul class="opt">
<li>
<label>
<input type="radio" name="date" />Date 1</label>
</li>
<li>
<label>
<input type="radio" name="date" />Date 2</label>
</li>
<li>
<input type="submit" value="submit"/>
</li>
</ul>
</li>
</ul>
</form>
</div>
<div id="results">
Filtered results go here
</div>
<script>
$("ul.opt").addClass("hidden");
$('#filter > li > a').on("click", function (e) {
var cache = $(this).next('ul');
$('#filter ul:visible').not(cache).hide();
cache.toggle();
$('#filter li input[type=submit]').hide();
});
$('#filter input[type=radio]').click(function() {
var $form = $(this).closest('form');
$('#results').html('filtering...');
$.post($form.attr('action'),$form.serialize(),function(response) {
if ( response ) {
$('#results').html(response);
} else {
$('#results').html('no results found');
}
});
});
</script>

Categories