Display selected radio button value on the panel title - javascript

I want to display the selected radio button value on a panel title.
This is my js file
$(document).ready(function(){
$(".child_option_radio").on("change", function(){
elem = $(this);
if ($(this).is(':checked'))
{
alert($(this).val());
}
$("#part_child_" + elem.attr("data-option-subid")).html(e);
alert("#part_child_" + elem.attr("data-option-subid"));
});
My part_child.erb file
<div class="row">
<%= options_radio_tag part_child, class: "child_option_radio", "data-option-subid" => part_child.id, "data-option-name" => part_child.name %>
</div>
This is my helper file for option_radio_tag for part child
def options_radio_tag(part_child)
html = ""
attr_name = "order[part][#{part_child.parent.id}][children][][part] [#{part_child.id}][option][][id]"
part_child.options.each do |o|
html += "<div class='col-sm-2'>"
html += label_tag "#{attr_name}", raw("<input id='order_part_#{part_child.id}_option_#{o.id}', data-option-subid='option_subid_#{o.id}', data-option-name='#{o.name}', name='#{attr_name}' type='radio' value='#{o.id}' #{o.is_default? ? 'checked' : ''} data-option-subid='option_subid_#{o.id}'> #{o.name}")
html += "</div>"
end
html.html_safe
end
Please let me know If you need any more details.
PS: With the above code I am getting this
wrong number of arguments (2 for 1)

You are trying to use a variable e which is not present in the handler method
$(document).ready(function () {
$(".child_option_radio").on("change", function () {
var elem = $(this);
if (this.checked) {
$("#part_child_" + elem.attr("data-option-subid")).html(this.value);
}
});
});

$(document).ready(function(){
$(".child_option_radio").on("change", function(){
elem = $("input[type=radio]:checked.child_option_radio");
alert(elem.val()); // Will give you the value of selected radio button
$("#part_child_" + elem.attr("data-option-subid")).html(elem.val());
});

Related

jquery- On onchange event tab content is not getting displayed properly

Below is my HTML code:
<select id="sourceNameDropdownId" label="condition " style="width:300px;">
</select>
<div id="tabs" class="selector">
</div>
Here, is my javascript code:
$("#DropdownId").change(function () {
var sid= $("#DropdownId option:selected").text();
afterclick(sid);
});
I am calling an onchange event on dropdown list, and the selected value i am passing to function afterclick
function afterclick(sid){
var tabsContainer = document.getElementById("tabs");
var crawlTab=document.createElement("ul");
//here in my actual code i am making a ajax call to fetch values for crawlList, providing static values here
var crawlList=["name1","name2","name3","name4"];
$.each(crawlList, function( index, crawlType ) {
var crawlTabElement=document.createElement("li");
crawlTabElement.innerHTML= '' +crawlType+'';
crawlTab.appendChild(crawlTabElement);
});
tabsContainer.appendChild(crawlTab);
var count=1;var tabCount=1;
$.each(crawlList, function( index, crawlType ) {
var contentCrawlTab=document.createElement("div");
contentCrawlTab.setAttribute("id",crawlType);
var p='<p>'+crawlType+'</p>';
contentCrawlTab.innerHTML=p;
tabsContainer.appendChild(contentCrawlTab);
});
$( ".selector" ).tabs();
}
This code is working fine when for the first time page gets loaded and a value is selected from the dropdown, but when i re-select value from the dropdown tabs are not getting displayed properly.
This is when i select value for the first time after page is loaded.
And when i reselect the value from dropdown its showing like this-
Is there something like reload to reload the tabs div entirely, as it seems that its appending the previous values and next time when afterclick function is called tab elements are not getting displayed properly.
I tried clearing the "tabs" div too, using **$( "#tabs " ).empty()**But it didn't worked for me.
Please help me out.
Check this working code.
$().ready(function () {
$(".selector").tabs();
$("#DropdownId").change(function () {
var sid = $("#DropdownId option:selected").text();
afterclick(sid);
});
});
function afterclick(sid) {
var tabsContainer = document.getElementById("tabs");
tabsContainer.innerHTML = '';
var crawlTab = document.createElement("ul");
//here in my actual code i am making a ajax call to fetch values for crawlList, providing static values here
var crawlList = [sid + "1", sid + "2", sid + "3", sid + "4"];
$.each(crawlList, function (index, crawlType) {
if (crawlType != null) {
var crawlTabElement = document.createElement("li");
crawlTabElement.innerHTML = '' + crawlType + '';
crawlTab.appendChild(crawlTabElement);
}
});
tabsContainer.appendChild(crawlTab);
var count = 1; var tabCount = 1;
$.each(crawlList, function (index, crawlType) {
if (crawlType != null) {
var contentCrawlTab = document.createElement("div");
contentCrawlTab.setAttribute("id", crawlType);
var p = '<p>' + crawlType + '</p>';
contentCrawlTab.innerHTML = p;
tabsContainer.appendChild(contentCrawlTab);
}
});
$(".selector").tabs('destroy');
$(".selector").tabs();
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<select id="DropdownId" label="condition " style="width:300px;">
<option selected="selected" disabled="disabled">--Select--</option>
<option>Bilna-ID</option>
<option>IndiatimesShopping</option>
</select>
<div id="tabs" class="selector">
</div>

Jquery Click send doesn't work

Hi everyone i have one question about jquery click send function. I have created this demo from jsfiddle. So if you visit the demo then you can see there is one smiley and textarea. When you write some text and press enter then the message sending successfully. But i want to add also when you click the smiley then it need to send (w1) from the image sticker="(w1)" like click to send. But click send function doesn't work. What is the problem on there and what is the solution ? Anyone can help me in this regard ?
JS
$('.sendcomment').bind('keydown', function (e) {
if (e.keyCode == 13) {
var ID = $(this).attr("data-msgid");
var comment = $(this).val();
if ($.trim(comment).length == 0) {
$("#commentload" + ID).text("Plese write your comment!");
} else {
$("#commentload" + ID).text(comment);
$("#commentid" + ID).val('').css("height", "35px").focus();
}
}
});
/**/
$(document).ready(function() {
$('body').on("click",'.emo', function() {
var ID = $(this).attr("data-msgid");
var comment = $(this).val();
if ($.trim(comment).length == 0) {
$("#commentload" + ID).text("nothing!");
} else {
$("#commentload" + ID).text(comment);
$("#commentid" + ID).val('').css("height", "35px").focus();
}
});
});
$('body').on('click', '.sm-sticker', function(event) {
event.preventDefault();
var theComment = $(this).parents('.container').find('.sendcomment');
var id = $(this).attr('id');
var sticker = $(this).attr('sticker');
var msg = jQuery.trim(theComment.val());
if(msg == ''){
var sp = '';
} else {
var sp = ' ';
}
theComment.val(jQuery.trim(msg + sp + sticker + sp));
});
HTML
<div class="container one">
<div class="comments-area" id="commentload47">comments will be come here</div>
<div class="user-post" id="postbody47">
<textarea class="sendcomment" name="comment" id="commentid47" data-msgid="47"></textarea>
<div class="stiemo">
<img src="http://d.lanrentuku.com/down/png/1009/networking/emoticon_inlove.png" class="sm-sticker emo" sticker="(w1)"> click smiley to send (w1)</div>
</div>
</div>
</div>
try this :
just append below JS after the line theComment.val(jQuery.trim(msg + sp + sticker + sp));
var e = $.Event("keydown");
e.keyCode = 13; // # Some key code value
$('.sendcomment').trigger(e);
Demo
you should use this:
$('body').on("click",'.emo', function() {
var ID = $('.sendcomment').attr("data-msgid");
var comment = $('.sendcomment').val();
if ($.trim(comment).length == 0) {
$("#commentload" + ID).text("nothing!");
} else {
$("#commentload" + ID).text(comment);
$("#commentid" + ID).val('').css("height", "35px").focus();
}
});
so basically instead of this you have to use input and get msgid and val from there, use same approach for rest.
So when you are attaching event on some button and you want to use data from some other dom element you have to get that element by using $(selector) under your delegated function, really simple approach.

Selectors ignoring Ajax / Jquery loaded content

I'm working with a static json file. I'm using jquery to load my file into my store.
Everything loads fine.
At the side of my store, I have a categories menu, where I can filter my store items.
Because my store is items are dynamically generated, I dont seem to be able to select them with jquery.
Here is the ajax request:
<script>
$(function () {
var actionUrl = '#Url.Action("Items", "Home")';
$.getJSON(actionUrl, displayData);
function displayData(response) {
if (response != null) {
for (var i = 0; i < response.length; i++) {
$("#store").append("<div class='storeItem' data-price=" + response[i].PriceScale + " data-category=" + response[i].Cat + "> <img src='#" + response[i].Cat + "' class='itemImage' alt='" + response[i].Title + "'/><span class='itemTitle'>" + response[i].Title + "</span><span class='itemDesc'><p>" + response[i].Desc + "</p></span><span class='itemPrice'>"+ response[i].Price +"</span><a href='#' class='add2cart'>ADD TO CART</a>")
}
}
else {
$("#store").append("<h5>There was a problem loading the store content.</h5>");
}
}
});
</script>
Here is the code I have tride:
<script>
$(function () {
$( "nav#catagories ul li input").on("click", function () {
var a = $(this).prop("checked");
var b = $(this).attr("id");
if (a == true) {
$("div.storeItem").hide();
$(".storeItem").data("category", b).show();
}
});
});
</script>
I've also tried:
<script>
$(function () {
$(document).on("click","nav#catagories ul li input", function () {
var a = $(this).prop("checked");
var b = $(this).attr("id");
if (a == true) {
$("div.storeItem").hide();
$(".storeItem").data("category", b).show();
}
});
});
</script>
In both cases the script works up untill the div.storeItem hide.
Here is the HTML that is outputed:
<div class="storeItem" data-price="med" data-category="apparel">
<img src="#apparel" class="itemImage" alt="Shirt">
<span class="itemTitle">Shirt</span>
<span class="itemDesc">
<p>A Beatiful Shirt</p>
</span>
<span class="itemPrice">23.45</span>
ADD TO CART
</div>
Maybe your problem doesn't have to do anything with items being dynamically generated. Here $(".storeItem").data("category", b).show(); you are replacing category value with value stored in b, while it seems you want to select those which has category equal to b.
Maybe this will work or at least give you the direction:
$(function () {
$(document).on("click", "nav#catagories ul li input", function () {
var checked = $(this).prop("checked");
var category = $(this).attr("id");
if (checked) {
$(".storeItem").hide()
.filter(function () {
return $(this).data("category") === category;
}).show();
}
});
});

Jquery: Changing a value on a page as you check and uncheck checkboxe

I have this line of code that exist in a partial view. Jquery code resides in the index page hosting the partial view
<div class="paythisamountbtn">#Html.ActionLink(T("Pay This Amount"), "InvoiceCheckout", null, new { #target = "InvoiceCheckout", #class = "amebtn" }): #String.Format("{0:C}", Model.TotalDue)</div>
I have a checkbox on every row of data. This is all within a webgrid. Here is what it looks like below
#{
var gridColumns = new List<WebGridColumn>();
gridColumns.Add(grid.Column(format: (item) =>
{
var s = "<input type=\"checkbox\" name=\"InvoiceNumber\" id=\"IN" + item.InvoiceNumber.ToString() + "\" value=\"" + item.InvoiceNumber.ToString() + "|" + item.AmountDue + "\"";
if (item.IsSelected) {
s += "checked=\"true\"";
}
s+= "/>";
return s;
}
, style: "box"));
...
...
...
}
function SetViewSelected(c) {
var s = 0;
for (i = 0; i < $("input[name='InvoiceNumber']:checked").length; i++) {
invoice_details = $("input[name='InvoiceNumber']:checked")[i].value;
invoice_amount = invoice_details.split("|")[1];
s += parseFloat(invoice_amount);
}
alert(s);
//$('.paythisamountbtn').val(s);
}
As I check and uncheck the checkboxes, I want to be able to show the total on the line below as they change. At the moment the alert(s) gets me the new total
<div class="paythisamountbtn">#Html.ActionLink(T("Pay This Amount"), "InvoiceCheckout", null, new { #target = "InvoiceCheckout", #class = "amebtn" }): #String.Format("{0:C}", Model.TotalDue)</div>
I tried doing $('.paythisamountbtn').val(s); but the totaldue does not change as I check and uncheck the check boxes.
How can I do this please?
Use .text for a div
$('.paythisamountbtn').text(s)
To update the attribute value what you must do is the following:
$('.paythisamountbtn').text(parseInt($('.paythisamountbtn').text())+5);
To update the value each time you click one of the checkboxes you could do something like this:
$('#checkbox1').change(function() {
if($(this).is(":checked")) {
UpdateValueNow();
}
});

Corresponding answer buttons disappear within an appended row

I have a jsfiddle here which you can use to see a basic demo of my application and the problem I am having.
When you open fiddle please follow these steps below:
You will see an "Open Grid" link, click on the link and select either "True or False" or "Yes or No" buttons.
After selecting either of the buttons you will see their answer buttons appear underneath.
Please click on the "Add Question" button and this will appended a table row into the table underneath.
Now in the appended row is the problem. If you click on the "Open Grid" link within the appended row and select either of the buttons, you will realise that the corresponding answer buttons underneath disappears. They should be displayed not disappear.
So my question is that can anyone modify the demo so that they can get the corresponding answer buttons to appear within the appended row when the user clicks on the "Open Grid" link in the appended row?
I think the problem maybe within this code but I am not sure:
var count = 0;
var plusbutton_clicked;
var gQuestionIndex = 0;
function insertQuestion(form) {
var context = $('#optionAndAnswer');
var currenttotal = context.find('.answerBtnsOn').length;
var $tbody = $('#qandatbl > tbody');
var $tr = $("<tr class='optionAndAnswer' align='center'>");
var $td = $("<td class='extratd'>");
var $options = $("<div class='option'>1. Option Type:<br/></div>");
var $answer = $("<div class='answer'>3. Answer:<br/></div>");
gQuestionIndex++;
$('.gridTxt', context).each(function() {
var $this = $(this);
var $optionsText = $("<input type='text' class='gridTxtRow maxRow' readonly='readonly' />").attr('name', $this.attr('name') + "[]").attr('value', $this.val()).appendTo($options).after("<span href='#' class='showGrid'>[Open Grid]</span>");
$questionType = $this.val();
});
var $this, i = 0,
$row, $cell;
$('#optionAndAnswer .answers').each(function() {
$this = $(this);
if (i % 7 == 0) {
$row = $("<tr/>").appendTo($answer);
$cell = $("<td/>").appendTo($row);
}
var $newBtn = $(("<input class='answerBtnsRow answers' type='button' style='display:%s;' onclick='btnclick(this, " + gQuestionIndex + ");' />").replace('%s', $this.is(':visible') ? 'inline-block' : 'none')).attr('name', "value[" + gQuestionIndex + "][]").attr('value', $this.val()).attr('class', $this.attr('class')).attr('id', $this.attr('id') + 'Row');
$newBtn.appendTo($cell);
i++;
});
$tr.append($td);
$td.append($options);
$td.append($answer);
$tbody.append($tr);
count++;
$('#optionAndAnswer .answerBtns').hide();
$('#optionAndAnswer .answerBtns').removeClass('answerBtnsOn').addClass('answerBtnsOff');
updateAnswer($answer, gQuestionIndex);
}
Thanks
I think the main problems may be in insertQuestion().
As far as I can tell :
$cell is defined conditionally but the line $newBtn.appendTo($cell); is unconditional. When the condition is not met, the append statement will fail silently (no error message).
even on the occasions that the condition is met $newBtn is successfully appended to $cell, and $cell is appended to $row, but $row is never appended to anything. Consequently no newBtns will appear in the DOM.
Edit:
Try replacing :
if (clickedNumber === 'True or False') {
$(this).closest('.option').siblings('.answer').find('input[name="answerName[True]"]').show();
$(this).closest('.option').siblings('.answer').find('input[name="answerName[False]"]').show();
} else if (clickedNumber === 'Yes or No') {
$(this).closest('.option').siblings('.answer').find('input[name="answerName[Yes]"]').show();
$(this).closest('.option').siblings('.answer').find('input[name="answerName[No]"]').show();
}
with :
var ans = $(this).closest('.option').siblings('.answer').find('input');
if (clickedNumber === 'True or False') {
ans.filter('[value="True"], [value="False"]').show();
} else if (clickedNumber === 'Yes or No') {
ans.filter('[value="Yes"], [value="No"]').show();
}

Categories