Adding ID to button, but must change based on radio input selection - javascript

EDITED TO ADD HTML: not exactly the same since im not in my office anymore, but you'll get the idea.
The scenario is i have a part of a site where users can pick 1 of multiple addresses they have saved. The ID gets generated for each address and I need to apply that ID to a button to submit the form.
I've gotten it so the button receives the ID from the first click, but if I try to select a different address, the ID will not switch. How can I have the button use the ID of the most recently selected radio input? I'm using a data attribute to select this.
HTML:
<div>
<form>
<input type="radio" data-js="select" id="Test123" /> (id created dynamically)
<label>Address 1</label>
<input type="radio" dat-js="select" id="Test124" /> (id created dynamically)
<label>Address 2</label>
</form>
</div>
<button class="address-continue">Continue</button>
var radioID = $('*[data-js]').attr('id');
var addrContinue = $('.address-continue');
$('*[data-js]').click(function () {
$(addrContinue).attr('id', radioID);
});
Scenario: user clicks on address 1, so ID is then placed on the button for address 1. user made a mistake, meant to click on address 2. currently when i click address 2, the ID on the button doesn't change. it remains the same as the original click.
I need the ID on the continue button to change based on the proper radio selection.

Since id is unique use class
$('*[data-js]').click(function () {
var addrButton = $('.address-continue');
addrButton.removeClass(test123);
addrButton.removeClass(test124);
radioID = $('*[data-js]').attr('id');
addrButton.addClass(radioID);
});
Also your basic problem might be because you did not collect your radioID in ur radio function hence it wasn't updated so try this
$('*[data-js]').click(function () {
var radioID = $('*[data-js]').attr('id');
$(addrContinue).attr('id', radioID);
});

The following should do it for you hoping the corresponding elements are in the same order:
$('[data-js]').on('change',function() {
$('.address-continue').data('id', this.id);
});
$('.address-continue').on('click',function() {
alert( $(this).data('id') );
});
You cannot assign a second element in your document the id of another. IDs should be unique; therefore I have used data-id.
$('[data-js]').on('change',function() {
$('.address-continue').data('id', this.id);
});
$('.address-continue').on('click',function() {
alert( $(this).data('id') );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<form>
<input type="radio" name="address" data-js="select" id="Test123" /> (id created dynamically)
<label>Address 1</label>
<input type="radio" name="address" data-js="select" id="Test124" /> (id created dynamically)
<label>Address 2</label>
</form>
</div>
<button class="address-continue">Continue</button>

Related

How to control related text input element with a button?

I have a list of text-field + button that gets rendered dynamically. The user hits the button and I want to control the input field when a button is clicked.
I figure you could do something like:
<input id="1"><button onclick="doSomething(1)">Something</button>
<input id="2"><button onclick="doSomething(2)">Something</button>
<!--...-->
<input id="3"><button onclick="doSomething(3)">Something</button>
But wonder if there's a different and more sophisticated solution because the code I'm modifying passes an an anonymous function to onclick and I can't pass a unique ID like the method above.
This is very easy to achieve in vanilla Javascript (as most things). No jQuery overhead required here.
let buttons = [...document.getElementsByClassName('inputbutton')]
function doSomething(i) {
console.log(i);
}
for (const button of buttons) {
button.addEventListener('click', (e) => {
const i = e.target.previousSibling.id
doSomething(i);
})
}
<input id="1"><button class="inputbutton" type="button">Something</button>
<input id="2"><button class="inputbutton" type="button">Something</button>
<!--...-->
<input id="3"><button class="inputbutton" type="button">Something</button>
If you modify your dynamic HTML like the following and add this jQuery, you will be able to access the value of the previous input field.
var buttons = $(".inputs-and-buttons #button-after-input-field");
buttons.click(function() {
console.log($(this).prev("input").val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inputs-and-buttons">
<input id="1" value="1"><button id="button-after-input-field">Something</button>
<input id="2" value="2"><button id="button-after-input-field">Something</button>
<!--...-->
<input id="3" value="3"><button id="button-after-input-field">Something</button>
</div>
You can generate dynamic Id for both input field and button with index or row number or you can add custom attribute for row number as below.
You can generate dynamic related control with specific Id for textbox and button as well. e.g. txtFirstName_1, txtLastName_1, btnAdd_1. here textbox and button distinguished by its id and number after Underscore "_" .
$(function(){
// Register click on button
//here you can pass specific class name for button if all are have same functionality
$("button").click(function(e){
console.log(this);
var btnId=$(this).attr("id");
//console.log(btnId);
// Way 1
//Split btnId with "_" e.g btn_1 will splited with ["btn","1"]
var rowIndex=btnId.split("_")[1];
console.log(btnId.split("_"),rowIndex);
$("#txt_"+rowIndex).val("Upate value by btn"+rowIndex); // Or fetch value
// Way 2
// You can directly use custom attribute data-row and do your work
var rowIndex1=$(this).attr("data-row");//$(e).prop("data-row");
console.log(rowIndex1);
//$("#txt_"+rowIndex1).val("Upate value"); // Or fetch value
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="txt_1" data-row="1"><button id="btn_1" data-row="1">Something</button>
<input id="txt_2" data-row="2"><button id="btn_2" data-row="2">Something</button>
<input id="txt_3" data-row="3"> <button id="btn_3" data-row="3">Something</button>

Selected value of Radio Button doesn't change

In the view, I have these two radio buttons:
#Html.RadioButtonFor(c => c.CampaignType, "Exclusive")<label>Exclusive</label>
#Html.RadioButtonFor(c => c.CampaignType, "Shared")<label>Shared</label>
The value for Model.CampaignType is set in the controller before the page loads. All of this works fine. If Exclusive is what's saved in the DB, then we get this rendered in the HTML:
<input checked="checked" id="CampaignType" name="CampaignType" type="radio" value="Exclusive"><label>Exclusive</label>
<input id="CampaignType" name="CampaignType" type="radio" value="Shared"><label>Shared</label>
So far, all's well.
But, inside an onclick() event for a button, if I do this:
var values =
{
"CampaignType": $('#CampaignType').val()
}
alert(values.CampaignType);
The alert always comes up as `Exclusive', even if I have changed the selection to 'Shared'.
What do I need to do so that values.CampaignType reflects the what is selected on the page, and not what was set when the page was loaded?
So you can do start with these:
Remove the invalid ids - multiple ids are invalid in CSS. For getting the value of the checked radio button you can use:
$('input[name=CampaignType]:checked').val()
or
$('input[type=radio]:checked').val()
For the label to work you have to link it with the corresponding radio button using the for attribute.
See demo below:
function submit() {
var values = {
"CampaignType": $('input[name=CampaignType]:checked').val()
}
console.log(values.CampaignType);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input checked="checked" id="CampaignType1" name="CampaignType" type="radio" value="Exclusive">
<label for="CampaignType1">Exclusive</label>
<input id="CampaignType2" name="CampaignType" type="radio" value="Shared">
<label for="CampaignType2">Shared</label>
<br/>
<button onclick="submit()">click here</button>
All the best!

Show hide text box from a dynamic element jQuery c#

Below is my code, I am trying to hide and show dynamic elements. The problem I am having is, I only want my hidden div to only show one at a time if only I check "Other". However, the code below will show the hidden div for all number of #dynamicRows I have. so it works for initial 1st #dynamicRow added, the problem is when I have two or more #dynamicRows
$('#dynamicRow').on('click', 'input[id^=race]', function () {
if ($(this).is(":checked")) {
if ($(this).val() == "Other") {
$(".cssclass").each(function (index) {
$(this).closest("div").show();
});
}
else {
$(".cssclass").each(function () {
$(this).closest("div").hide();
});
}
}
});
Below are dynamic rows, for help purposes i am showing the html code, however, it doesn't exist on the screen, a user will click "ADD" to generate the code below. I have no problem in generating dynamic row and it is not why I am posting. note the name in my radio button is generated by c# and everything works. Again the problem is not how to create a dynamic row, it is nicely taken care of in C#.
Dynamic row one works with the above jQuery:
<div id="dynamicRow">
<input type="radio" value="No" id="race[]" name="Person[hhhhhh].race"> No:
<input type="radio" value="Other" id="race[]" name="Person[hhhhhh].race"> Other:
<div id="iamhidden" class="cssclass">
I appear one at a time, when other radio button is checked
</div>
</div>
Dynamic row two doesn't work with the above jquery and it takes the above form events as its own, so if i check the radio button in row 2, the 1st dynamic row responds to that event and vice versa:
<div id="dynamicRow">
<input type="radio" value="No" id="race[]" name="Person[hhhhh].race"> No:
<input type="radio" value="Other" id="race[]" name="Person[hhhhh].race"> Other:
<div id="iamhidden" class="cssclass">
I appear one at a time, when other radio button is checked
</div>
</div>
Working Example
id should be unique in same document, replace the duplicate ones by a class :
<input type="radio" value="No" class="race" name="Person[hhhhhh].race"> No:
<input type="radio" value="Other" class="race" name="Person[hhhhhh].race"> Other:
Also add class and not id to the dynamic rows generated by your C# code :
<div class="dynamicRow">
Then in your js use this class :
$(".cssclass").hide();
$('.dynamicRow').on('click', '.race', function () {
if ($(this).val() == "Other") {
$(this).next(".cssclass").show();
} else {
$(this).nextAll(".cssclass").hide();
}
});
Hope this helps.
Try this:
$('body').on('click', '#dynamicRow', function () {
if ($(this).find('[value=Other]').is(":checked")) {
$(".cssclass").each(function (index) {
$(this).closest("div").show();
});
} else {
$(".cssclass").each(function () {
$(this).closest("div").hide();
});
}
});
He is a working example of what you wanted. I am generating the required with js only.
Few Points to mention
you add the event listener to the parent of the dynamic generated content.
Avoid use of IDs if they are not going to be unique and prefer classes and pseudo selectors if required
var counter = 0;
function addNewEntry(){
++counter;
var str = '<div class="dynamicRow"><input type="radio" value="No" id="race[]" name="Person[hh'+counter+'].race"> No:<input type="radio" value="Other" id="race[]" name="Person[hh'+counter+'].race"> Other:<div id="iamhidden" class="cssclass"> I appear one at a time, when other radio button is checked</div> </div>';
$('#dynamicRowContainer').append(str);
$("#dynamicRowContainer .dynamicRow:last-child .cssclass").hide()
}
$('#dynamicRowContainer').on('change', '.dynamicRow > input', function () {
if(this.value=="Other"){
$(this).siblings('.cssclass').show();
}else{
$(this).siblings('.cssclass').hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="addNewEntry()">Add New Entry</button>
<div id="dynamicRowContainer">
</div>

How to rename a html form elements' Id attribute using Jquery?

I have a form which contains radio boxes.
<input type="radio" name="categoryid" id="category420" value="420" onclick="checkCategory();" > Category1
<input type="radio" name="categoryid" id="category1314" value="13,14" onclick="checkCategory();" >Category2
<input type="radio" name="categoryid" id="category594" value="594" onclick="checkCategory();" >Category3
When the radio elements value attribute is a comma separated list (13,14) I need the elements Id attribute to change.
In the example above, when the second category is selected then "CategoryIDs=13,14" should be passed to the action page not categoryid. But for the other two categories it should pass categoryid value.
I cannot edit the action page.
The question: How can I change the radio buttons Id attribute in JQuery?
Change the Id
Based on your requirement to have only one Id (categoryid/s) then you could change the Id using JQuery, before the form is submitted.
JSFiddle working example - http://jsfiddle.net/daTYY/
JQuery
$(function() {
$('input:radio[name=categoryid]').change(function() {
if ($(this).val().indexOf(",") >= 0) {
$(this).attr("id","newId");
}
});
});
Update a hidden input
Add a hidden input named categoryids. Then use JQuery to check if categoryid contains a comma and if it does populate categoryids with the value.
JSFiddle working example - http://jsfiddle.net/KVs79/
HTML
<input type="radio" name="categoryid" id="categoryid1" value="13,14" />Category2
<input type="radio" name="categoryid" id="categoryid2" value="404" />Category3
<input type="hidden" name="categoryids" id="categoryids" value="" />
JQuery
$(function() {
$('input:radio[name=categoryid]').change(function() {
if ($(this).val().indexOf(",") >= 0) {
$("#categoryids").val("13,14");
}else{
$("#categoryids").val("");
}
});
});

If radio button checked add new form element using dom?

How do I use DOM in Javascript to check if a radio button is checked and then if so add new form elements to datesettings?
//Radio buttons
<input type="radio" id="dateoption" name="dateoption" value="1">
<input type="radio" id="dateoption" name="dateoption" value="2">
//Add new form elements
<span id="datesettings"></span>
Im currently reading a Javascript book but its not helping me understand. If someone could help me with this example then maybe the penny will drop. Thanks for your time.
Check out this page:
It explains the process so you understand why you're doing it a certain way, AND it gives good example code.
http://www.webdevelopersnotes.com/tips/html/finding_the_value_of_a_radio_button.php3
You would write a function to do the check, like this:
function CheckDateOptions() {
var o1 = document.getElementById("dateoption1");
var o2 = document.getElementById("dateoption2");
var eSettings = document.getElementById("datesettings");
if(o1.checked) {
eSettings.appendChild(...);
}
else if(o2.checked) {
eSettings.appendChild(...);
}
}
But, you have to make sure to assign your radio buttons unique id values. You can duplicate names to group the radio buttons, but for any element, the id should be unique.
<form id="TestForm">
<!-- //Radio buttons -->
<input type="radio" id="dateoption1" name="dateoption" value="1">Text 1</input>
<input type="radio" id="dateoption2" name="dateoption" value="2">Text 2</text>
<!-- //Add new form elements -->
<span id="datesettings"></span>
</form>

Categories

Resources