Get the selected option/value of a dynamic select field in RAILS - javascript

I have here a select_field with a dynamic ID.
Why dynamic? Because I used a nested field/form.
<%= f.select :category_id, Category.all.map{ |c| [c.code, c.id] }, {prompt:""},{class:"cat-code"} %>
I have here a JS code that simply gets the dynamic id per select field.
<%= javascript_tag do %>
$(function() {
$(".cat-code").change(function(){
var getID = this.id;
var value = $("getID").val()
alert(value);
if (value == "1"){
$(".div1").show();
$(".div2").hide();
}
else if (value == "2"){
$(".div1").hide();
$(".div2").show();
}
});
});
<% end %>
I can get the id using..
alert(getID);
But getting the selected value turns undefined which results the show() and hide() divs for not working too.
Any workarounds will be appreciated. Thanks.

var value = $("#" + getID).val()

var element = $(this);
var value = element.val()

Thank you guys, already solved this using.
$(".cat-code").change(function(){
var getID = this.id;
var value = document.getElementById(this.id).value;
console.log(getID + "with a value of" + value);
if (value == ){
$(".div1").show();
$(".div2").hide();
}
else if (value == "2"){
$(".div1").hide();
$(".div2").show();
}
});

Related

Assigning a variable in Javascript

I have defined index as <%var index = 0;%> This is at the top of the body of HTML so I can use it throughout as a global variable.
and I want to assign value of $(this).val() to <% index %>.
I have tried multiple times but am not able to figure it out.
I am using Node.js in backend and EJS in front end.
<script>
$("#agency").on("change", function () {
var $modal = $('#myModal');
if($(this).val() !== '0'){
<% index %> = parseInt($(this).val()); ????
}
$modal.modal('show');
}
});
</script>
As someone mentioned you need to differentiate between what is calculated on the server and what is done on the browser:
A common page might look like:
<script>
var index = <% index_calculated_on_server %>;
$("#agency").on("change", function () {
var $modal = $('#myModal');
if($(this).val() !== '0'){
index = parseInt($(this).val()); ????
}
$modal.modal('show');
}
});
</script>
Your problem lies in mixing server-side and client-side rendering. To illustrate, let's take a look at the snippet you provided.
<script>
$("#agency").on("change", function () {
var $modal = $('#myModal');
if($(this).val() !== '0'){
<% index %> = parseInt($(this).val()); // This is the problem line
}
$modal.modal('show');
}
});
</script>
EJS is rendered before even being sent to the client, merging in variables provided to it, so if you set index to be zero, you'll end up with a snippet like this after the rendering is done.
<script>
$("#agency").on("change", function () {
var $modal = $('#myModal');
if($(this).val() !== '0'){
0 = parseInt($(this).val()); // Can't assign zero.
}
$modal.modal('show');
}
});
</script>
Instead, what you should do is wrap your use of <% index %> in a wrapper element, which should allow you to manipulate it client side.
$("#agency").on("change", function () {
var $modal = $('#myModal');
if( $(this).val() !== '0' ) {
$(".index-counter").text(parseInt($(this).val()));
}
$modal.modal = function () { /* stub function */ };
$modal.modal('show');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" name="agency" id="agency" />
<!-- This would be where <% index %> was inserted -->
<div class="index-counter">0</div>

JS add attribute to string

I have a post ajax that return retorno1 and just to get it simple i put their output as string value as ajax posted like the example .. then I need to add more than 1 option that the value is 0 so I need to say if the value is 0 show the selected item "NON" and if the value other so show it and select it.
I'm using setAttribute("selected", "selected") but I know it's wrong, so what is the correct code to add attribute to this string?
var i = 0;
var returno1 = "<option value='21'>Hello</option><option value='22'>Bye</option>";
var pre = retorno1 + '<option value="0">------ N/A ------</option>';
var count = $($.parseHTML(pre)).filter('option').length;
var dep_dr = $("#departamento_drop option:selected").val();
$.each($.parseHTML(pre),function(i,item){
var val_drop =($(item).val());
var text_drop =($(item).html());
if (val_drop == dep_dr){
jQuery("#departamento_drop").html(pre).setAttribute("selected", "selected");
}else if(dep_dr == "0"){
jQuery("#departamento_drop").html(pre).setAttribute("selected", "selected");
}
})
Working fiddle
Try to use attr() or prop() to set or get attribute to elements, check example bellow :
jQuery("#departamento_drop").empty();
$.each($.parseHTML(pre),function(i,item){
var current_itme=$(item);
var val_drop =current_itme.val();
var text_drop =current_itme.html();
if (val_drop == dep_dr || dep_dr == "0"){
current_itme=current_itme.attr("selected", "selected");
}
jQuery("#departamento_drop").append(current_itme);
})
Hope this helps.
Why do you need use strings? Use objects insted.
var values = [{val:33, title:'Hi'},{val:34, title:'Bue'},{val:0, title:'-------NA-------'}],
selected = 34;
values.forEach(function(item){
$('#dd').append($('<option>', {value:item.val, text:item.title, selected: item.val==selected}));
})

mvc 4 How to call javascript function after #Html.RadioButtonFor clicked

View Has :
<div Monthly #Html.RadioButtonFor(m => m.DDPaymentOption, "Monthly", true)
Yearly #Html.RadioButtonFor(m => m.DDPaymentOption, "Yearly", true)
</div>
tried
$(":radio").click(function () {
var Selectedvalue = $(this).val();
var isDiv = document.getElementById('instalmentScheduleDiv');
if (Selectedvalue == "Yearly")
{
isDiv.className = "HideDiv";
}
});
Does not hit the function
Use this code
$('#DDPaymentOption').click(function(){
if($(this).val()=='Yearly')
{
$('#instalmentScheduleDiv').addClass('HideDiv');
}
});
And if you are using HideDiv Class to hide the div you can jquery methods to show or hide your div element like
$('#instalmentScheduleDiv').hide(); // to hide the element
and/or
$('#instalmentScheduleDiv').show(); // to show the element
$("input[type=radio]").change(function () {
var Selectedvalue = $(this).val();
var isDiv = $("#instalmentScheduleDiv");
if (Selectedvalue == "Yearly")
{
isDiv.hide();
} else {
isDiv.show();
}
});
All credit goes to: codingbiz
This is how you can do this.
function updatePostID(val)
{
document.getElementById('PostID').value = val;
//and probably call document.forms[0].submit();
}
Then have a hidden field or other control for the PostID
#Html.Hidden("PostID", Model.addcomment.PostID)
//OR
#Html.HiddenFor(model => model.addcomment.PostID)
How do I update a model value in JavaScript in a Razor view?

In javascript get the value of dropdown

I am populating values in drop down from the database. The every text have values. I want to select the values using JavaScript..
My code
<%= Html.DropDownList("Role", ViewData["Role"] as SelectList,"Select" , new {onchange = "javascript:ddlRoleChanged();", id="ddlRoles", #class = "dropdownStyle2"})%>
Javascript code:
<script type="text/jscript">
$(document).ready(function () {
var tempDDVal = '<%= Session["Function"] %>';
$("#ddlRoles option:contains(" + tempDDVal + ")").attr('selected', 'selected');
});
function ddlRoleChanged() {
debugger;
var selectvalue = document.getElementById('#ddlRoles');
var selectedValue = $('#ddlRoles').val();
window.location = '/home?func=' + selectedValue.valueOf();
};
</script>
But selectedvalue is showing only the text values.. How to take that?
You want the selected item from #ddlRoles. Try this:
var selectedValue = $('#ddlRoles option:selected').val();
window.location = '/home?func=' + selectedValue;
jQuery('#Dropdown').change(function(){
var DropdownValue = jQuery(this).children('option:selected').val();
});
put your values in data property on your ELEMENT.
$("ELEMENT").attr('data-value', 'MYDATA');
and after you can get it
$("ELEMENT").attr('data-value');

To get the text of the selected item in the dropdown list in java script

I want to get the text of the selected item in the drop down list. I tried the following code
var e = document.getElementById("ddlTime.ClientID");
var selectedTime = e.options[e.selectedIndex].text;
but it gives me "Unable to get value of the property 'options': object is null or undefined"
can any one please help me out with this ?
You should do:
var e = document.getElementById("<%= ddlTime.ClientID%>");
Not:
var e = document.getElementById("ddlTime.ClientID");
My little sample jsfiddle
You have to specify <%= %>
var e = document.getElementById("<%= ddlTime.ClientID%>");
JavaScript
function WeekChange() {
var Week = window.document.getElementById("ddWeek").value;
if (Week != "--Select--") {
window.document.getElementById("txtDetect").value = "Every " + Week;
}
else {
window.document.getElementById("txtDetect").value = " ";
}
}
<asp:DropDownList ID="ddWeek" runat="server" onchange="javascript:WeekChange();">

Categories

Resources