I have an anchor tag that has an href. I need to add a string after the last / in the href from an input text box. I have tried to add the value of the input box to the href with no success. Can I add the value to the link string using the onclick event? How can this get accomplish using jquery? Here is the code:
//This is the Search Button
$('#switch-fighter-search-button-link').attr("href","/fighters/search/");
//This is the Input box
var sft = $('$switch-fighter开发者_开发知识库-text').val();
This way it'll take the href of the original link and add the value of the element with id "switch-fighter-text"
$('#switch-fighter-search-button-link').click(function(){
window.location=$(this).attr("href")+$('#switch-fighter-text').val();
return false;
});
Not exactly sure what you're trying to do here but if you could provide more code that would be useful. Here's an example of what I think you might be trying to do:
<script type="text/javascript>
$('#submit').click(function(){
var $link = $('#link1');
//add to the href
$link.attr('href', $link.attr('href') + "?id=1");
});
//note that if you want to prevent the link from submitting do like so
$('#link1').click(function(){
//force redirect to a specific url, adding to the href on the fly
window.location = $(this).attr('href') + "&user=me";
return false; //prevents href from changing window.location
});
</script>
<body>
<input id="submit1" type="Submit" value="Submit"></input>
<a id="link1" href="somelink/test.html">Link</a>
</body>
Something like this should work:
$('$switch-fighter-text').change(function() {
var link = $('#switch-fighter-search-button-link');
link.attr('href', link.attr('href') + $(this).val());
});
$('#switch-fighter-search-button-link').attr("href", $('#switch-fighter-search-button-link').attr("href") + $('$switch-fighter-text').val() );
This will add your textbox's value to the already existing href src
but i think that can change the href src after you clicked on the page will not work. So use
onclick=" window.location='"' + $('#switch-fighter-search-button-link').attr("href") + $('$switch-fighter-text').val(); + '"'; "
$('#switch-fighter-search-button-link').click(function(){
window.location="/fighters/search/"+$('$switch-fighter-text').val();
return false;
});
精彩评论