How to change part of url (ID) using radio button? - javascript

I got some radio buttons pushed by a loop in JSP:
<input type="radio" name="radioBtn" value="<s:property value="#country.getIdCountry()"/>">
The value of the radio button describe the ID of a country it selects.
Then I created some links eg.:
<a href='addDefaultPoints.action?countryId=<s:property value="#country.getIdCountry()"/>&height=400&width=350'>Link 1</a>
<a href='editCountryMap.action?height=550&width=750&id=<s:property value="#country.getIdCountry()"/>&keepThis=true&TB_iframe=true'>Link 2</a>
I would like to change code into some dynamic page, that can change the ID on the onChange event of the radio button set, within an url specified in href.
I tried using Javascript for this functionality, but with no luck. Perhaps I need to do this on the server side. I am using JSP, struts, Jquery and Javascript.
Here is what I tried:
var myGetValue = parseURL("id");
function checkV(f,v){
for(var i=0;i<c.length;i++){
c[i].checked=(c[i].value==v)?true:false;
}
}
checkV(myForm,myGetValue);

You can write below logic :
create url in hidden input with some constant name for county id, use same class name for corresponding anchor tag
<input class="COUNTY_ID" type="hidden" value="addDefaultPoints.action?countryId=COUNTY_ID&height=400&width=350">
<a class="COUNTY_ID" href="#"/>
write change event for radio button :
$('input[name="radioBtn"]').change(function(){
var radioVal = $(this).val();
var url = $('input[class="COUNTY_ID"]').val();
url = url.replace('COUNTY_ID',radioVal);
$('a[class="COUNTY_ID"]').attr('href',url);
});
Use similar logic for other links also ...

HTML
<input type="radio" name="radioBtn" value="1">
<input type="radio" name="radioBtn" value="2" checked>
<input type="radio" name="radioBtn" value="3">
<input type="radio" name="radioBtn" value="4">
<a id="lnk1" href='addDefaultPoints.action?height=400&width=350&countryId='>Link 1</a>
<a id="lnk2" href='editCountryMap.action?height=550&width=750&keepThis=true&TB_iframe=true&id='>Link 2</a>
JS
$(document).ready(function() {
var countryId = $('input[name=radioBtn]:checked').val();
$('a#lnk1').attr('href', $('a#lnk1').attr('href') + countryId);
$('a#lnk2').attr('href', $('a#lnk2').attr('href') + countryId);
});
Explanation
First you get the selected country by checking the checked radiobutton of the group radioBtn.
Then you make sure that the country param of your url is at the end so that you can concatenate the countryId to the rest of your links attribute 'href'.
Result
Link1: addDefaultPoints.action?height=400&width=350&countryId=2
Link2: editCountryMap.action?height=550&width=750&keepThis=true&TB_iframe=true&id=2
If the param is not ad the end of the link then you can use the replace() function like Bhushan Kawadkar mentioned.

Related

Trying to dynamically replace a url &option value based on <input> button

I'm trying to dynamically replace a url value, i'm using replace because i don't want the value to be duplicated on every click
I'm certainly not the best coder in the world, and i'm not sure if my syntax is valid or not.
The general idea i'm trying to accomplish below is there are several urls on the page, only one is shown at any given time i use a slider to hide/show each url in a seamless manner.
I want to pass a location to the javascript function (it will be a number) and that function should take the location number and replace the section in all href="" on the page.
But i can't seem to get it to work.
function getlocation(loc) {
$('a').each(function() {
var location = $(this).attr('href');
$(this).attr('href').replace("&location=100", "&location=loc");
console.log('error');
});
}
<a class="button" href="#get.php&location=100">Test</a>
<br>
<br>
<a class="button" href="#get.php&location=100">Test</a>
<br>
<br>
<feildset>
<input id="mtl" name="location" type="radio" checked>
<label for="mtl" onclick="getlocation(mtl)">Montreal</label>
<br>
<br>
<input id="frkfrt" name="location" type="radio" onclick="">
<label for="frkfrt" onclick="getlocation(frkfrt)">Frankfurt</label>
</feildset>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
frkfrt and mtl are not variables - you want to pass it as a string. But inline event handlers are as bad as eval inside HTML - attach the handler properly using Javascript instead, to make problems like these less likely.
replace does not mutate the original string - strings are immutable. Instead, you need to explicitly assign to the hrefs in order to change them.
In getlocation, you have to concatenate the loc variable with the &location=
['mtl', 'frkfrt'].forEach(loc => {
document.querySelector(`[for="${loc}"]`).onclick = () => getlocation(loc);
});
function getlocation(loc) {
document.querySelectorAll('a').forEach(a => {
a.href = a.href.replace(/&location=.*$/, "&location=" + loc);
});
}
<a class="button" href="#get.php&location=100">Test</a>
<br>
<br>
<a class="button" href="#get.php&location=100">Test</a>
<br>
<br>
<feildset>
<input id="mtl" name="location" type="radio" checked>
<label for="mtl">Montreal</label>
<br>
<br>
<input id="frkfrt" name="location" type="radio">
<label for="frkfrt">Frankfurt</label>
</feildset>
If I well understand what you need, try replace
$(this).attr('href').replace("&location=100", "&location=loc");
with
$(this).attr('href').replace("&location=100", "&location=" + loc);

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!

Dynamically created form from database and accessing elements with jquery

I have form that is created from database. Form contains radio buttons which are created like this
<label>
<input type="radio" name="rizici_radio<?php echo $riz_id ?>"
value="<?php echo $rizik['riz_vrednost_da']; ?>" >
<?php echo $rizik['riz_vrednost_da']; ?>
</label>
Name attribute contains rizici_radio and id from database. And every row has pair of radio buttons with values 1 or 0.
So my problem is manipulating changing values of that pair of radio buttons. For example when i select radio button with value 1 it should fill span tag with value of changed radio button. And i have another span where sum of values from all span tags should be displayed.
Grey is span where value of selected radio button should be stored
Using loop might create issue as some times loop counter value and DB ID's might differ. So what you need to do set DB ID to both radio button set like below where i am setting rel-id value to DB Ids
<label><input type="radio" class="promena" rel-id = '2' name="rizici_radio2" value="1" >1</label>
<label><input type="radio" class="promena" checked rel-id = '2' name="rizici_radio2" value="0">0</label>
And use below jquery code
$(".promena").on("change",function(){ // bind a function to the change event
if( $(this).is(":checked") ){ // check if the radio is checked
var val = $(this).val(); // retrieve the value
var id = $(this).attr("rel-id");
$("#bodovi"+id).val(val); //setting value to respective hidden field
$("#scores"+id).text(val); // showing selected radio button value in gray area
}
});
Hope this helps you.
with jQuery:
$(radiobutton selector here).click(function(){
$(this).next(".greyValueArea").val($(this).val());
})
This should do the trick. just change selectors.
"Selectors i must create from id's. That is my main problem. I must use something like for loop to add id to either name or id"
#Thug you can also give them some class that they would be having incommon.
You see: If you make a
$('.button').on("click",function(){
console.log($this)
})
It will console log button class item you clicked and it applies to every button class you have
First of all, I think it would be better to request the table data with an ajax request as json data from server if you need to update the server data later.
Anyway, for getting the clicked row you can also use the following script:
$('.selectionForm').on('change', 'input[type="radio"]',
function(event) {
console.log('changed radio', $(this).attr('name'), $(this).val(), $(this).parent().find('span'));
$(this).parent().find('span').text($(this).val());
});
It goes up in the DOM to the parent of the clicked radio button and then with find you're going down again to the span of that row.
It uses event delegation because that's required for dynamically added content from the ajax request. That would be not required for the PHP added content.
Please see the demo below and here at jsfiddle.
Handlebars.registerHelper('isChecked', function(input, options) {
//console.log(input, this);
//console.log(this, this.value, input);
return this.value === input? 'checked': '';
});
var $out = $('#out'),
rowTmpl = $("#row-template").html(),
template = Handlebars.compile(rowTmpl);
$.ajax({
url: 'http://www.mocky.io/v2/556d9fd9e822500114253f39',
jsonp: 'callback',
dataType: "jsonp",
success: function(response) {
console.log(response);
$.each(response, function(index, data) {
//console.log(data);
$out.append(template(data));
});
}
});
$('.selectionForm').on('change', 'input[type="radio"]', function(event) {
console.log('changed radio', $(this).attr('name'), $(this).val(), $(this).parent().find('span'));
$(this).parent().find('span').text($(this).val());
});
//$out.html(JSON.stringify(dataArray));
ul {
list-style-type: none;
}
li {
border-bottom: 1px solid gray;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.3/handlebars.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>form loaded with ajax request:</h1>
<p>table generated with javascript</p>
<form class="selectionForm">
<ul id="out"></ul>
<!--<ul>
<li>
<input type="radio" name="row0" value="0"/>0
<input type="radio" checked="" name="row0" value="1"/>1
<span class="badge">1</span>
</li>
<li>
<input type="radio" name="row1" value="0"/>0
<input type="radio" checked="" name="row1" value="1"/>1
<span class="badge">1</span>
</li>
</ul>-->
</form>
<script id="row-template" type="text/x-handlebars-template">
<li>
<input type="radio" value="0" name="row{{id}}" {{isChecked 0 }}/>0
<input type="radio" value="1" name="row{{id}}" {{isChecked 1 }}/>1
<span class="badge">{{value}}</span>
</li>
</script>
<h1>form generated with server side script</h1>
<form class="selectionForm">
<ul>
<li>
<input type="radio" name="row0" value="0"/>0
<input type="radio" checked="" name="row0" value="1"/>1
<span class="badge">1</span>
</li>
<li>
<input type="radio" name="row1" value="0"/>0
<input type="radio" checked="" name="row1" value="1"/>1
<span class="badge">1</span>
</li>
</ul>
</form>

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