I have an HTML form with multiple select dropdowns (most of the jQuery snippets I've found online talk about multi-selects which are different, i.e. checkboxes.)
How can you use jQuery to collect/join the values from all the dropdown fields, and separate them with a symbol i.e. comma or plus sign? Then, send to URL (WordPress tag search).
I've tried this code and it doesn't work:
<script>
jQuery(document).ready(function() {
jQuery("#submit").click(function() {
var tags = $(".option").map(function() {
return ($(this).text() == "") ? null : $(this).text(); // ignore default
// return $(this).text(); // include all values
}).join("+");
window.location = "<?php echo home_url( '/' ); ?>/tag/" + tags;
return false;
});
});
</script>
Here's the latest version, with .get added, still no luck:
<script>
jQuery(document).ready(function() {
jQuery("#submit").click(function() {
var tags = $(".option").map(function() {
return ($(this).text() == "") ? null : $(this).text(); // ignore default
// return $(this).text(); // include all values
}).get().join("+");
window.location = "<?php echo home_url( '/' ); ?>/tag/" + tags;
// return false; // tried this on and off
});
});
</script>
A couple things: 1) added .get() to get access to .join(), and 2) limited the return to only selected options that are not blank:
jQuery(document).ready(function() {
jQuery("#submit").click(function(evt) {
evt.preventDefault();
var tags = $(".option").map(function() {
return (this.selected && $(this).text() != "") ? $(this).text() : null;
}).get().join("+");
window.location = "<?php echo home_url( '/' ); ?>/tag/" + tags;
});
});
And for good measure, pulled in the event object and prevented the default action.
JSFiddle: http://jsfiddle.net/jKGP8/
You should use get() in combination with jquery map function, otherwise you receive not just array but jQuery object
var tags = $(".option").map(function() {
return ($(this).text() == "") ? null : $(this).text(); // ignore default
}).get().join("+");
$("#result").html(tags);
http://jsfiddle.net/tx8HT/
With on click you should just replace your old var tags = .. string with new tag calculation.
<script>
jQuery(document).ready(function() {
jQuery("#submit").click(function() {
var tags = $("#form .option").map(function() {
return ($(this).text() == "") ? null : $(this).text(); // ignore default
}).get().join("+");
window.location.href = "<?php echo home_url( '/' ); ?>/tag/" + tags;
return false;
});
});
</script>
Looks like your jQuery selector is wrong, should be "option" rather than ".option" (your code is looking for elements with the class "option"). Also, this will concatenate all select option text values, not just the ones that the user has selected. It is not clear if this is what you are after, but I thought I would give you a heads up.
Related
I write a form submit thread with the attr method:
var href = a.attr('href');
if(href =='') return;
if(href.startsWith('http') || href.startsWith('//:')){
a.attr('href',href.trim());
if(href.indexOf(location.hostname) > -1){
return;
}
if(href.indexOf('<?php echo $_SERVER['SERVER_NAME']; ?>') > -1){
return;
}
a.attr('href','go.htm?uri='+href);
a.attr('rel','nofollow');
}
However, it returns the URL without ?, for example, I want to return https://example.abc.com/?ref=abc, the return result will be https://example.abc.com/ref=abc without "?" the question mark.
I'm struggling with solving this and I appreciate any helpful tips.
You can use split function string. Split your URL with "?" and take first element.
var yourRequiredLink = href.replace("?", '')
this is my whole javascript code
what im trying to do here is loop through html table and look for checked checkbox and retrieve the data in every row of checked checkbox
but i need to run this is php.
<script type='text/javascript'>//<![CDATA[
$(window).load(function () {
$('#save').click(function () {
$('#dataTable').find('tr').each(function () {
var row = $(this);
if (row.find('input[type="checkbox"]').is(':checked') ) {
//alert('You must fill the text area!');
var $row1 = $(this).closest("tr"), // Finds the closest row <tr>
$tdi = $row1.find("td:nth-child(1)");
$.each($tdi, function () { // Visits every single <td> element
var thirdrowval = $(this).text(); // Prints out the text within the <td>
//document.getElementById("signatoryid").value = thirdrowval
alert(thirdrowval);
});
}
});
});
});//]]>
</script>
and after reading in this site i found a way to do it and here is the code. but it doesn't run the javascript. i expect an alert to pop up. but it doesn't worked as expected
$row1 = "";
$row = "";
$thirdrowval = "";
$tdi = "";
echo "
<script type=\"text/javascript\">
$('#dataTable').find('tr').each(function () {
var row = $(this);
if (row.find('input[type='checkbox']').is(':checked') ) {
var $row1 = $(this).closest('tr'),
$tdi = $row1.find('td:nth-child(1)');
$.each($tdi, function () {
var thirdrowval = $(this).text();
alert(thirdrowval);
});
}
});
</script>
";
Try to include your table $('#dataTable') also in your php file.
I think javascript can't find the element that named #dataTable
in the line
if (row.find('input[type='checkbox']').is(':checked') ) {
you will have to escape the inner quotes ' it should be
if (row.find('input[type=\'checkbox\']').is(':checked') ) {
also you have to pay attention that variables in strings with double quotes like
echo "$row1";
will be replaced with the value of the php variable $row1. So in your example it will be replaced with an empty string. If this is not the exspected behaviour you can use single quotes:
echo '$row1';
this will print $row1
I have a save button handler inside which i check the employee name , skills and level for the employee which can be in multiple. I need the best possible way to do it as i am certain the way i do it looks really messy. Thanks
JS code:
$("#btnSave").click(function(){
var empName = $("#empName").val().trim(); // VALIDATE THIS
var skillArr = [];
var empObj = {};
if(empName != '')
return false;
$(".trSkillCls").each(function( index ) {
// VALIDATE FOR skill and level
if($(this).find('input[name=skill]').val().trim() == '' || $(this).find('select[name=ddlSkillLevel] option:selected').text().trim() == '')
return false;
skillObj = {
"skill" : $(this).find('input[name=skill]').val(),
"level" : $(this).find('select[name=ddlSkillLevel] option:selected').text()
};
skillArr.push(skillObj);
});
empObj = {
"empName" : $("#empName").val(),
"skillDetails" : skillArr
};
$.post( "indexBase.php",
$('#str').val(JSON.stringify(empObj)),
function(info){
var result = JSON.parse(info);
$( "#divEmpDetails" ).empty();
$("#divEmpDetails").append($("#tmplEmpDetails").render({data:result}));
// verify this callback for failures
});
$("#mainForm").submit( function() {
return false;
});
$('.trSkillCls').not(':first').remove();
$( "#reset" ).trigger( "click" );
});
I'm new to JS. I have a script which should count clicks and store clicks number value in cookie. The problem is I can't correctly save and call clicks number(generated by parseInt) value from cookies.
Here is the code http://jsfiddle.net/csTpG/99/ (using jquery.cookie plugin)
$('#counter').click(function() {
var productID = $(this).attr('name');
var $this = $(this);
$.get('/', {
item_id: productID
}, function(response) {
if (response) {
if (response == 'empty')
$this.text('Count');
else
$this.text('Count (' + parseInt(response) + ')');
$.cookie('clicked-counter', 'true');
}
});
return false;
});
if ($.cookie('clicked-counter') == 'true') {
var cookie = $.cookie('clicked-counter');
$('#counter a').text('Count (' + cookie + ')');
};
#counter{background-color:white}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="counter">Counter</button>
Yup parseInt() shows NaN.
I updated your script to make it work (i included jQuery.cookie plugin for example) , look here http://jsfiddle.net/nicolapeluchetti/csTpG/100/ but there are still some issues. You get NaN when you do a parseInt because you are trying to parse an html page that returns from your ajax call. What are you trying to do?
I am trying to redirect English browsers to xyz.com/?lang=en while letting Swedish ones stay on xyz.com
I have been trying :
var type=navigator.appName
if (type=="Netscape")
var lang = navigator.language
else
var lang = navigator.userLanguage
//cut down to first 2 chars of country code
var lang = lang.substr(0,2)
// Swedish
if (lang == "sv")
window.location.replace('????')
// if none of above (default to English or any other)
else
window.location.replace('xyz.com/?lang=en')
</script>
But I don't know how to write the Swedish URL since it's not a redirection as the default language is swedish... writing the xyz.com gets me into a redirection loop
if ($_REQUEST["lang"] == "en")
{
echo '<div class="langlight">Svenska</div>';
}
else
{
echo '<div class="langbold">Svenska</div>';
}
if ($_REQUEST["lang"] == "en")
{
echo '<div class="langbold">English</div>';
}
else
{
echo '<div class="langlight">English</div>';
}
enter code here
if (lang !== "sv") {
window.location.replace(window.location.href + '?lang=en');
}
You are always checking the language from the navigator.
This way everytime the page loads it will try to reload the page with the altered or not url.
You need to place a condition where it will not reload the page..
That should be when there is a URL parameter passed.
So check for the querystring as well and override the default if a value exists in the url.
<script type="text/javascript">
(function(undefined){
var queryString = {},
search = window.location.search.substring(1), // read the current querystring
searchItems = search.length?search.split('&'):[]; // and split it at the different params if any exist
for(var i = 0, len = searchItems.length; i < len; i++){ // for each parameter passed
var parts = searchItems[i].split('='); // split the key/value pair
queryString[parts[0].toLowerCase()] = parts[1]; // and store it to our queryString variable
}
if (queryString.lang === undefined){ // if there is no lang parameter passed do your checking otherwise skip this step completely and use the url lang parameter.
var type=navigator.appName, lang = '';
if (type=="Netscape") {
lang = navigator.language.substr(0,2);
} else {
lang = navigator.userLanguage.substr(0,2);
}
if (lang != "sv"){
if (searchItems.length){
window.location.replace(window.location.href + '&lang=en');
} else {
window.location.replace(window.location.href + '?lang=en');
}
}
}
}());
</script>
Notice: Although, as #missingno mentions in his comment to your question, this is best handled server-side than client-side.