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

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);

Related

Multi step form - how to show data from steps before?

Is this a good solution to check multiple radio buttons with 1 label? I have a form with multiple steps. The last step shows a summary about the previous steps and I need to get all data from there. Is there a better option? How can I get the text from the input fields and insert it to the summary? JavaScript?
$('label').click(function() {
id = this.id.split('-');
if (id[0] === '1') {
id[0] = '2';
} else {
id[0] = '1';
}
$('#' + id[0] + '-' + id[1]).prop('checked', true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="one">
<input type="radio" id="1-1" name="1-level">
<label for="1-1" id="1-1">1</label>
<input type="radio" id="1-2" name="1-level">
<label for="1-2" id="1-2">2</label>
</div>
<div class="two">
<input type="radio" id="2-1" name="2-level">
<label for="2-1" id="2-1">1</label>
<input type="radio" id="2-2" name="2-level">
<label for="2-2" id="2-2">2</label>
</div>
Add a form element to wrap your input elements in. Forms can access all the inputs that are inside of it and see their names and their values. So in this case it is important that you use the value attribute on your input elements. Start by doing the above and make your code look like the example below.
Also, be careful with id's. They need to be unique, so they can only appear once in every document. Right now the label and their input elements have the same id.
<form id="step-form">
<div class="one">
...
</div>
</form>
Like #Shilly suggested, use the FormData API. This API is designed to get all the values from a form, think input, textarea and select elements and puts all of that data into a single object. This way you can create as many form-elements as you want, add them to the form and store their values in a single object.
The data in that object will be read as key-value pairs, which in this case are the name and value attribute values. For example: ['1-level', '2'], here we see the input with the name '1-level' and the value '2'.
I would not recommend using other input elements to show your results or summary. This could be confusing for the user as it suggests input. Instead print your results in plain text or create a list.
I do not know the jQuery equivalent of many of these API's or methods, so I've used Vanilla JavaScript to create a demo which, hopefully, demonstrates what you try to accomplish.
If you have any question, I've been unclear, or have not helped you in any way. Please let me know.
const form = document.getElementById('step-form');
const summary = document.getElementById('step-summary');
const clear = document.getElementById('step-clear');
// Remove all children of the summary list.
function clearSummary() {
while(summary.firstElementChild) {
summary.firstElementChild.remove();
}
}
// Clear list on click.
clear.addEventListener('click', event => {
clearSummary();
});
form.addEventListener('submit', event => {
// Clear list first.
clearSummary();
// Create a fragment to store the list items in.
// Get the data from the form.
const fragment = new DocumentFragment();
const formData = new FormData(event.target);
// Turn each entry into a list item which display
// the name of the input and its value.
// Add each list item to the fragment.
for (const [ name, value ] of formData) {
const listItem = document.createElement('li');
listItem.textContent = `${name}: ${value}`;
fragment.appendChild(listItem);
}
// Add all list items to the summary.
summary.appendChild(fragment);
event.preventDefault();
});
<form id="step-form">
<div class="one">
<input type="radio" id="1-1" name="1-level" value="1">
<label for="1-1">1</label>
<input type="radio" id="1-2" name="1-level" value="2">
<label for="1-2">2</label>
</div>
<div class="two">
<input type="radio" id="2-1" name="2-level" value="1">
<label for="2-1">1</label>
<input type="radio" id="2-2" name="2-level" value="2">
<label for="2-2">2</label>
</div>
<div class="three">
<input type="radio" id="3-1" name="3-level" value="1">
<label for="3-1">1</label>
<input type="radio" id="3-2" name="3-level" value="2">
<label for="3-2">2</label>
</div>
<ul id="step-summary"></ul>
<button type="submit">Review form</button>
<button type="button" id="step-clear">Clear summary</button>
</form>

JavaScript change value and data from value in a span

I need help with this. I need to make the value in the other place change all the time while user session is active. How can I get the value from a span and make other value in a data change?
Look at there!
1 <div class="pt-uea-container">
2 <span class="pt-uea-currency pt-uea-currency-before"> € </span>
3 <input type="text" class="pt-field pt-uea-custom-amount" autocomplete="off" name="pt_items[1][amount]" id="pt_uea_custom_amount_1" value="199" placeholder="" data-parsley-errors-container="#pt_uea_custom_amount_errors_1">
4 <input type="hidden" class="pt-field pt-uea-custom-amount-formatted" name="pt_items[1][amount]" value="199" data-pt-price="199">
5 <input type="hidden" name="pt_items[1][label]" value="Amount:">
6 <input type="hidden" name="pt_items[1][tax_percentage]" value="0">
7 <input type="hidden" name="pt_items[1][type]" value="open">
8 <div id="pt_uea_custom_amount_errors_1"></div>
9 <span class="form-price-value">85</span>
10 </div>
The value in row 9 needs to constantly change values in row 3 and 4 on the same session. Don't mind the value in row 6.
Let me know how I can get this done. Or maybe a different approach?
Greetings!
========
So this is what I got for now from you guys:
jQuery(document).ready(function($) {
var checkViewport = setInterval(function() {
var spanVal = $('.form-price-value').text();
$('#pt_uea_custom_amount_1').val(spanVal);
$('#pt_uea_custom_amount_formatted_1').val(spanVal);
$('#pt_uea_custom_amount_formatted_1').attr('data-pt-price', spanVal);
}, 1000);
});
This code works, but it only affects my needs when I put my mouse in pt-field pt-uea-custom-amount and add a space in it. Then it does apply to the page source. But this is not correct. The source needs to get changed too without touching that class or a space or something!
You can easily do this with the help of jQuery.
With the help of jQuery I would do like this.
Understanding what input field needs to be tracked for changes. I will give all this field a class (track-me).
In the document ready, I will look for changes for that tracked field.
On change of that field I will get the value and put in other input fields (class copy-to - or you can do whatever you like).
See an example below,
HTML
<form>
<div class="">
<input type="text" class="track-me" value=""/>
</div>
<div class="">
<input type="text" class="copy-to" value=""/>
</div>
<div class="">
<input type="text" class="copy-to" value=""/>
</div>
<div class="">
<input type="text" class="copy-to" value=""/>
</div>
<div class="">
<div class="">Please type anything in the first input box</div>
</div>
</form>
jQuery
$(document).ready(function(){
$('.track-me').change(function (){
$('.copy-to').val($(this).val())
});
});
I made comments in the above jQuery code so you can understand. Also, I have made a fiddle so you can play and have a look. In this fiddle, I am using Bootstrap4 just for the purpose of styling, you don't have to worry about that.
Link to fiddle
https://jsfiddle.net/anjanasilva/r21u4fmh/21/
I hope this helps. Feel free to ask me any questions if you have. Cheers.
This is not an ideal solution. I'm not sure there is a verified way of listening for when the innerHTML of a span element changes. This sort of stuff is usually based on user interaction, and the value of the span will be modified by your page. The best solution would be to use the same method that updates the span element to update the values of you hidden input fields.
However, I've placed an interval that will run every second, that takes the text value of the span element and gives it to the values of the 2 input fields:
function start() {
setInterval(function() {
document.getElementById("pt_uea_custom_amount_1").value = document.getElementById("price_value").innerHTML;
document.getElementById("pt_uea_custom_amount_2").value = document.getElementById("price_value").innerHTML;
}, 1000);
}
window.onload = start();
<div class="pt-uea-container">
<span class="pt-uea-currency pt-uea-currency-before"> € </span>
<input type="text" class="pt-field pt-uea-custom-amount" autocomplete="off" name="pt_items[1][amount]" id="pt_uea_custom_amount_1" value="199" placeholder="" data-parsley-errors-container="#pt_uea_custom_amount_errors_1">
<input type="hidden" class="pt-field pt-uea-custom-amount-formatted" name="pt_items[1][amount]" value="199" data-pt-price="199" id="pt_uea_custom_amount_2">
<input type="hidden" name="pt_items[1][label]" value="Amount:">
<input type="hidden" name="pt_items[1][tax_percentage]" value="0">
<input type="hidden" name="pt_items[1][type]" value="open">
<div id="pt_uea_custom_amount_errors_1"></div>
<span id="price_value" class="form-price-value">85</span>
</div>
MutationObserver should work here..
const formValuePrice = document.querySelector( '.form-price-value' );
const inputText = document.querySelector( 'input[type="text"]' );
// timer to change values
window.setInterval( () => {
formValuePrice.textContent = Math.round( Math.random() * 100 );
}, 1000 );
// mutation observer
const observer = new MutationObserver( ( mutationsList ) => {
inputText.value = formValuePrice.textContent;
} );
observer.observe( formValuePrice, { childList: true } );
https://codepen.io/anon/pen/LgWXrz?editors=1111
try this, simple using jquery, you can check in inspect element for value attribute data-pt-price
Update: you can using jquery event .on() like change, click, keyup or else to Attach an event handler function for one or more events to the selected elements,
you can read the doc here.
here the updated code
$(function() {
var spanVal = $('#price_value').text();
$('#pt_uea_custom_amount_1').val(spanVal);
$('#pt_uea_custom_amount_formatted_1').val(spanVal);
$('#pt_uea_custom_amount_formatted_1').attr('data-pt-price', spanVal);
$('#pt_uea_custom_amount_1').on('change click keyup', function() {
$('#pt_uea_custom_amount_formatted_1').val($(this).val());
$('#price_value').text($(this).val());
$('#pt_uea_custom_amount_formatted_1').attr('data-pt-price', $(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pt-uea-container">
<span class="pt-uea-currency pt-uea-currency-before"> € </span>
<input type="text" class="pt-field pt-uea-custom-amount" autocomplete="off" name="pt_items[1][amount]" id="pt_uea_custom_amount_1" value="199" placeholder="" data-parsley-errors-container="#pt_uea_custom_amount_errors_1">
<input type="hidden" class="pt-field pt-uea-custom-amount-formatted" name="pt_items[1][amount]" value="199" data-pt-price="199" id="pt_uea_custom_amount_2">
<input type="hidden" name="pt_items[1][label]" value="Amount:">
<input type="hidden" name="pt_items[1][tax_percentage]" value="0">
<input type="hidden" name="pt_items[1][type]" value="open">
<div id="pt_uea_custom_amount_errors_1"></div>
<span id="price_value" class="form-price-value">85</span>
</div>

Is it possible to have my button run three separate functions based on what I have selected?

i'm trying to make a unit converter with multiple selections for different units like KG > LBS, Celsius to Fahrenheit.
document.getElementById('button').addEventListener('click', convert, false);
I need that convert to change based on my selection within the html is this possible?
<form>
<fieldset>
<label for="fValue">
Enter first value
</label>
<input type="number" id="fValue" />
</fieldset>
<fieldset>
<form action="">
<input type="radio" name="conv" id="but1" onclick="but1();"> Temp
<br>
<input type="radio" name="conv" id="but2" onclick="but2();"> Distance
<br>
<input type="radio" name="conv" id="but3"> Weight
</form>
<button type="button" id="button">Convert to</button>
</fieldset>
<fieldset>
<p>Results</p>
<p id="cValue"> </p>
</fieldset>
</form>
Yes. Just assign your button's event listener a function that checks what is selected in your HTML and then call another function that will do the math you want.
function checkSelection() {
// Where selection* is whatever you want to check for.
if(selection1){
do_math_1();
}
else if(selection2 and selection3) {
do_math_2();
}
else {
do_math_3();
}
}
funcion do_math_1(){
// Whatever you want to do.
}
funcion do_math_2(){
// Whatever you want to do.
}
funcion do_math_3(){
// Whatever you want to do.
}
document.getElementById('button').addEventListener('click', checkSelection);
You can't easily directly have it within this line of JavaScript, but if you made a function that wrapped the three different functions (for example function convertSelect() {}) and called that, then within it you could check to see what is selected, and call the correct function.
You could make an anonymous function like document.getElementById('button').addEventListener('click', function() {...}, false); if you wanted, but it would probably be wise to make it it's own function for clarity's sake.

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

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.

how to change color of text following function in javascript

Ok before i make spaghetti of this code i thought id ask around here. ive made a quiz for an online site.
The answers are stored in an array, and ive a function that checks the answers array to what youve clicked. then it counts them and gives you your score.
but i want to change the clor of the right answer wen the user clicks the score button. so the correct answers are highlighted. something like this https://www.shutterpoint.com/Home-Quiz.cfm (just hit submit at the bottom, no need to do the quiz).
the little answer icon at the side looks flashy but id rather just have the text change color. heres how my questions are formatted
<p>Film speed refers to:</p>
<p id = "question1">
<input type="radio" name="question1" id="Wrong" value = "a" onClick = "recordAnswer(1,this.value)"/>How long it takes to develop film. <br/>
<input type="radio" name="question1" id="Wrong" value = "b" onClick = "recordAnswer(1,this.value)"/>How fast film moves through film-transport system. <br/>
<input type="radio" name="question1" id="Answer" value = "c" onClick = "recordAnswer(1,this.value)"/> How sensitive the film is to light. <br/>
<input type="radio" name="question1" id="Wrong" value = "d" onClick = "recordAnswer(1,this.value)"/> None of these makes sense. <br/></p>
and these are the two functions that are called throughout. record answer is called every time the user clicks a button
function recordAnswer(question,answer)
{
answers[question-1] = answer;
}
this is the final button which calculates the score
function scoreQuiz()
{
var totalCorrect = 0;
for(var count = 0; count<correctAnswers.length;count++)
{
if(answers[count]== correctAnswers[count])
totalCorrect++;
}
<!--
alert("You scored " + totalCorrect + " out of 12 correct!");
-->
}
another function is best i think. ive already made attempts at it and know i have to set the color using
document.getElementById('Answer').style.color = '#0000ff';
onyl problem is 'Answer' doesnt seem to be registering. anyone shed some light?
ok so i cant have two or more of the same ids.
what about
if(value == correctAnswers[])
{
// change the color.
}
QUICK RESPONCE:
USE <P>
<p>
<input type="radio" name="question_1" class="wrong" value="a" />
How long it takes to develop film.
</p>
THEN
if(value == correctAnswers[])
{
YOUR_ELEMENT.parentNode.style.color = 'green';
}
IMPROVEMENT
DEMO: http://jsbin.com/aceze/26
hi Overtone!
first of all you need to restyle a litte your HTML schema!
you have multiple id="Wrong" instead of class="Wrong"
then here how your code should look:
var answers = { 1:'a' , 2:'f' , 3:'h' };
function checkQuestions() {
var form_elements = document.question_form.elements.length;
for ( var i = 0; i < form_elements; i++ )
{
var type = question_form.elements[i].type;
if ( type == "radio" ){
var quest = question_form.elements[i];
//if ( quest.checked ) {
var question_index = parseInt(quest.name.split('_')[1]);
//}
if ( quest.value == answers[question_index] ) {
quest.parentNode.style.border = '1px solid green';
quest.parentNode.style.color = 'green';
} else {
//quest.parentNode.style.border = '1px solid red';
quest.parentNode.style.color = 'red';
}
}
}
}
USE a FORM and one time SUBMIT BUTTON instead of adding onclick to each RADIO like this
<form name="question_form" id="question_form" method="POST" action='#'>
<div id="question_1"> <H4>QUESTIONS TIME 1</H4>
</div>
<p>
<input type="radio" name="question_1" class="wrong" value="a" />
How long it takes to develop film.
</p>
<p>
<input type="radio" name="question_1" class="wrong" value="b" />
How fast film moves through film-transport system.
</p>
<p>
<input type="radio" name="question_1" class="answer" value="c" />
How sensitive the film is to light.
</p>
<p>
<input type="radio" name="question_1" class="wrong" value="d" />
None of these makes sense.
</p>
...
...
<input type="radio" name="question_2" class="wrong" value="h" />
<span>None of these makes sense.
</span>
</p>
<input type="submit" name="submit" onclick="checkQuestions();return false;" value="submit"/>
</form>
PS: demo example updated with style... for sake!
You should format your ids in a more usable way.. I'd suggest something similar to questionNUMBER_answerVALUE.
Then it'd be a simple matter of...
for (var i=0; i<correctAnswers;i++) {
document.getElementById("question" + (i+1) + "_answer" + correctAnswers[i].toUpperCase()).style.color = "#0000FF";
};
Just check I've got your zero/non-zero indexing correct with regard to question/ answer numbers.
Instead of using a <p> I would consider using a <label for='question1_answerA'>How long it takes to develop film.</label>. You can still use a jQuery selector to find it and it feels more semantically correct. You will then also be able to select the option by clicking the text.
Although your other HTML isn't semantically correct. You need to give each radio a unique ID.
Obligatory jquery solution:
var highlightCorrect = function(){
$(".Answer").css("color", "#00FF00");
}
This is all assuming that you fix your HTML to use classes rather than IDs for "Wrong" and "Answer".

Categories

Resources