Replace href on select change - javascript

I have a select element with options with values that are some numbers (some id's).
<select id="select">
<option value="21">Random<option>
<option value="23">Random 2<option>
<option value="25">Random 3<option>
<option value="27">Random 4<option>
</select>
Next to it is a submit button that will preform some kind of submit.
<a class="button" href="www.random.org">Click me!</a>
I need to add the ?id= to that link, with the id value of the select. I created the code, but the issue is that it just appends the ?id= every time I change the select the option
var id;
$('#select').on('change', function(){
id = $(this).val();
var new_href = $('.button').attr('href') + '?id=' + id;
$('.button').attr('href', new_href);
});
So when I click on first option I get, for the href
www.random.org?id=21
But if I click on second one (or any for that matter) I get
www.random.org?id=21?id=23
It appends the id. How to 'clear' the previous id on change, and replace with the selected one? What am I doing wrong?

This should work.
var id;
var original_link = "www.random.org";
$('#select').on('change', function(){
$('.button').attr('href', original_link);
id = $(this).val();
var new_href = $('.button').attr('href') + '?id=' + id;
$('.button').attr('href', new_href);
});

you can try like this change button link
<a class="button" href="www.random.org" data-link="www.random.org">Click me!</a>
and change javascript like this
var id;
$('#select').on('change', function(){
id = $(this).val();
var new_href = $('.button').data('link') + '?id=' + id;
$('.button').attr('href', new_href);
});
I think it's helpful to you.

You can pass to .attr function as second argument, where you can replace url for .button, like so
$('#select').on('change', function(){
var id = $(this).val();
$('.button').attr('href', function (index, value) {
// if there is id in url - replace it, else add id to url
return /\?id=/.test(value) ? value.replace(/id=(\d+)/, 'id=' + id) : (value + '?id=' + id);
});
});
Example

Respecting every other answer, I would prefer a small amount of code:
$('#select').on('change', function(){
$( '.button' ).attr( 'href', $( '.button' ).attr( 'href' ).split( '?id=' )[0] + '?id=' + $( this ).val() );
});
This code actually splits the href when a ?id= exists and gives you only the part before it. When there is no ?id= than you get the normal href and after this, you just add ?id= and $( this ).val() to the href. (It's already in the code that I wrote)
That's it. No RegEx, Wordarounds or more lines of code than needed.

$target = $(".target");
$button = $(".button");
With jQuery you can $target.attr('href', $button.data('href-url') + '?id=' + id))

Check this
Demo
$('#select').on('change', function() {
var aLink = $('.button'),
selVal = $(this).val(),
staticLink = "www.random.org";
//alert(selVal)
$(aLink).attr('href', staticLink + "?id=" + selVal);
})

Related

Jquery: Stopping after 1st click

I am trying to implement edit functionality for a HTML element.
Right now my html-pug code is as below
div
label(for="todo" id="todo" + index class="ind-todo-list") test1
button(type="submit" id="todo" + index class="btn" onclick="editTodo()" ) Edit
button(type="submit" id="todo" + index class="btn" onclick="deleteTodo()" ) Delete
Jquery is as below
$(document).ready(function() {
$(".ind-todo-list").on("click" , function(){
var todoid = $(this).attr("id");
var newInput = document.createElement("input");
newInput.type="text";
newInput.name="todo";
$("#" + todoid).html(newInput);
});
});
But everytime I am clicking at the test1 my page reloading again even after input field added.
What I am trying to achieve is
- when I click at test1, I will have input box opened, where I can edit the test1 and save changes. But I am stuck here.
Thank you.
Edit 1
I have added event.preventDefault() but still experiencing same same
$(document).ready(function() {
$(".ind-todo-list").on("click" , function(event){
event.preventDefault();
var todoid = $(this).attr("id");
console.log("Todoid " + todoid);
console.log($("#" + todoid).html());
var newInput = document.createElement("input");
newInput.type="text";
newInput.name="todo";
//newInput.id=todoid;
//$("#" + todoid).html("<input type='text' name='todo' id='"+todoid+"'>");
$("#" + todoid).html(newInput);
});
Edit 2 - ID fix
div
label(for="todo" id="todo" + index class="ind-todo-list") #{todo.todo}
button(type="submit" id="todoedit" + index class="btn" ) Edit
button(type="submit" id="tododeleteq" + index class="btn" ) Delete
$(".ind-todo-list").on("click" , function(e){
//add an event to prevent default action on the element
e.preventDefault();
});
});

bootstrap select picker not working with input field

I have a select picker and I need to make that, when select language from this select picker gets a value from select and put into input filed.
The problem is that when i get value is success but after get show alert empty. and put value empty in field.
$(".m_selectpicker").selectpicker();
$(document).on('change', '.changeLanguage', function () {
var selectedLanguage = $(this).val();
alert(selectedLanguage);
$(this).parents('.countries').find('.lang').attr('name', 'name' + '[' + selectedLanguage + ']');
});
language
English
Arabic
Turkey
You can update the value attribute as well, see here https://jsfiddle.net/Lq2fz7dg/
$(document).on('change', '.changeLanguage', function () {
var selectedLanguage = $(this).val();
alert(selectedLanguage);
$(this).parents('.countries').find('.lang').attr('name', 'name' + '[' + selectedLanguage + ']');
$(this).parents('.countries').find('.lang').attr('value', selectedLanguage);
});
Update
This will work when .selectpicker() is initialized:
$(".m_selectpicker").on("changed.bs.select",
function(e, clickedIndex, newValue, oldValue) {
$('.lang').attr('name', 'name' + '[' + this.value + ']');
$('.lang').attr('value', this.value);
});
https://jsfiddle.net/no0r3qjf/

How i can get value form select > option, jquery

I have a problem with get value form select > option.
I make option that:
$.each(response, function(i, element)
{
var nazwaKategori = element.name;
var idKategori = element.id;
$("#kategoria").append("<option>KategoriaID:" + idKategori + ", Nazwa Kategorii:" + nazwaKategori + "</option>");
});
In body:
<form role="form">
<div class="form-group">
<label align="center" for="text">Lista dostępnych kategorii.</label>
<select class="form-control" id="kategoria">
<div id="kategoria">
</div>
</select>
<div id="wypisz"><div>
</div>
</form>
And i get this option:
<script>
$( "#kategoria" ).change(function () {
var str = "";
$( "#kategoria option:selected" ).each(function() {
str += $(this.KategoriaID).val() + " ";
});
$( "#wypisz" ).text( str );
})
.change();
</script>
How i can get only idKategori ? I musc find pattern in get text?
Thanks
Well apart of having a wrong html structure with a div inside a select, when you are creating your dropdown, you could use something like this:
$("#kategoria").append("<option value='"+idKategori+"'>KategoriaID:" + idKategori + ", Nazwa Kategorii:" + nazwaKategori + "</option>");
So every option will have a value and then in the change event you could use this:
$( "#kategoria" ).on("change", function () {
var optionselected = $(this).find(":selected").val();
//HEre you will have you value of the option selected in a variable
console.log(optionselected);
});
I don't know if thats what you wanted, and I don't know if your dropdown creation is working, but your questions is to get value from select option with jquery. Hope this helps

Add live text from input field to another div with Checkbox

I have an input field with Add button below it. Also have another Div class named .new-option-content
What I am trying to do is if anyone type something in the input filed and click the +ADD button this text of the input filed will append with a Check box inside .new-option-content div.
Here is the Fiddle
I tried with this but I guess with this process I can't get the result.
$( ".checklist-new-item-text" )
.keyup(function() {
var value = $( this ).val();
$( ".new-option-content" ).text( value );
})
.keyup();
I am not good with advance jquery. I did tried to find something similar but failed. I am not sure if this can be done with jquery.
Any help or suggestion will be appreciated.
$("#add").click(function(){
var newLabel = $("#optionInput").val();
if (!newLabel) return; //avoid adding empty checkboxes
var newOption = '<div class="checkbox"><label><input type="checkbox">' + newLabel +'</label></div>';
$(".new-option-content").append(newOption);
$("#optionInput").val(''); //clearing value
})
Fiddle: http://jsfiddle.net/has9L9Lh/8/
If you want to use it in multiple places on your page, you can try this modified version:
$(".new-option-add").click(function(){
var labelInput = $(this).parent().parent().find(".checklist-new-item-text")
var newLabel = labelInput.val()
if (!newLabel) return; //avoid adding empty checkboxes
var newOption = '<div class="checkbox"><label><input type="checkbox">' + newLabel +'</label></div>';
// where to append?
var listToAppend = $(this).attr("data")
$("." + listToAppend).append(newOption);
labelInput.val(''); //clearing value
})
We are using data attribute value on the button, to assign class name of the list, which need to be updated.
Fiddle: http://jsfiddle.net/has9L9Lh/18/
Here is how you can do it:
$(function() {
$('.new-option-add').on('click',function() {
var noc = $('.new-option-content'),
val = $('.checklist-new-item-text');
!val.val() || noc.append(
$('<div/>',{class:'checkbox'}).html(
$('<label/>').html( $('<input/>', {type:'checkbox'}) )
.append( ' ' )
.append( val.val() )
)
);
val.val('');
});
});
DEMO
And this should work for multiple sections:
$(function() {
$('.new-option-add').on('click',function() {
var section = $(this).closest('section'),
noc = $('.new-option-content', section),
val = $('.checklist-new-item-text', section);
!val.val() || noc.append(
$('<div/>',{class:'checkbox'}).html(
$('<label/>').html( $('<input/>', {type:'checkbox'}) )
.append( ' ' )
.append( val.val() )
)
);
val.val('');
});
});
DEMO
Many have answered, yet another option is to use .clone(), cause otherwise you can end up in a maintainence nightmare, so something like
$(".new-option-add").click(function() {
var checkbox = $(".checkbox:first").clone(), value;
value = $(".checklist-new-item-text").val();
checkbox.html(checkbox.html().replace('Sample 1', value));
checkbox.appendTo($(".new-option-content"));
})
http://jsfiddle.net/has9L9Lh/19/
you can do this by adding this code
on click event
$('#yourDiv').append(' <label><input id="chkbox" type="checkbox"> "+$('#yourText').val() +" </label>');

Append multiple dropdown values to URL

I'm trying to do something similar to this:
$('#dropdown1').change(function() {
window.location = $(this).val();
});
I need to build a page with 2 dropdown lists and a textbox, and I need the values for each one to be stored and then appended to the URL when the form is submitted.
The URL needs to look similar to this when all options have been selected:
http://www.domain.co.uk/search-results/?searchOptions=dropdown1=value1|dropdown2=value2|textarea1=value3
I've figured out how to store the values of the dropdowns but I can't seem to append it to the url.. Here's where I got to:
<script type="text/javascript">
function getValues() {
var priceTo = document.form.priceTo.value;
//alert (priceTo);
}
$(document).ready(function() {
//var zip = $('#zip').val();
var initialURL = 'http://www.domain.co.uk/search-results/?searchOptions=priceto='
$('#form').submit(function(e) {
window.location.href = initialURL + priceTo
return false;
});
});
</script>
<body>
<form id="form" name="form">
Price:
<select name="priceTo" id="priceTo" onchange="getValues()">
<option value="5000">Up to £5,000</option>
<option value="10000">Up to £10,000</option>
<option value="20000">Up to £20,000</option>
<option value="40000">Up to £40,000</option>
<option value="80000">Up to £80,000</option>
</select>
<input type="submit" id="submit" value="submit"/>
</form>
</body>
For some reason this goes to:
http://www.domain.co.uk/search-results/?searchOptions=priceto=[object%20HTMLSelectElement]
EDIT:
I finally got it working on most browsers, including IE8 with this code:
<script type="text/javascript">
$(document).ready(function() {
//var zip = $('#zip').val();
var initialURL = 'http://www.selektvolvocars.co.uk/selekt-search-results/?searchOptions='
$('#form').submit(function(e) {
window.location.href = initialURL + priceTo.options[priceTo.selectedIndex].value + model.options[model.selectedIndex].value + '%7Czipcode=' +document.getElementById('zip').value + '%7Cproximitydistance=50'
e.preventDefault();
});
});
</script>
For some reason though it doesn't work in IE9... makes no damn sense to me, it just spits out a completely jumbled up URL. Any ideas?
your priceTo is the select list. Use the following to get the selected value:
$('#form').submit(function(e) {
window.location.href = initialURL + priceTo.options[priceTo.selectedIndex].value
e.preventDefault();
});
If I've understood correctly:
var initialURL = 'http://www.domain.co.uk/search-results/?searchOptions=priceto='
$('#form').submit(function(e) {
window.location = initialURL + $("#priceTo").val() + "|" + $("#anyOtherSelects").val();
e.preventDefault();
});
You can remove the rest of the Javascript.
You can use a little helper function which gets the id of a <select> or <input> element and returns it with its value. For example:
<script type="text/javascript">
//Helper function to return id and value. The id parameter shouldn't have the # sign at its beginning
function getIdVal( id ) {
return id + "=" + encodeURIComponent( $("#"+id).val() );
}
//run this when the document is loaded and ready
$(document).ready(function() {
//var zip = $('#zip').val();
var initialURL = 'http://www.domain.co.uk/search-results/?'
$('#form').submit(function(e) {
window.location.href = initialURL + getIdVal( "priceFrom" ) + "|" + getIdVal( "priceTo" );
return false;
});
});
</script>
Notes:
You get the value of the current <option> selected in a <select> element using $(...).val().
It is a good programming practice to use encodeURIComponent() for encoding the values just to make sure that no strange character is going to break your convention of using = and | as record and field separator in the search query URL.

Categories