How to enter all multi-selection options into database - javascript

I have multi-selection functionality similar to this (see link): http://jsfiddle.net/eUDRV/341/.
HTML code:
<section class="container" >
<div>
<select id="list" name="list"size="15">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</div>
<div>
<br><br><br>
<input type="button" id="button_left" value="<--"/>
<input type="button" id="button_right" value="-->" />
</div>
<div>
<select id="selected_values" size="15"></select>
<input name="selected_values" type="hidden"/>
</div>
jQuery/Javascript code:
$(document).ready(function () {
$("#button_right").click(function () {
var selectedItem = $("#list option:selected");
var added = false;
$("#selected_values > option").each(function() {
if ($(this).text() > $(selectedItem).text()) {
$(selectedItem).insertBefore($(this));
added = true;
return false;
}
});
if(!added) $(selectedItem).appendTo($("#selected_values"));
updateHiddenField();
});
$("#button_left").click(function () {
var selectedItem = $("#selected_values option:selected"), activeValues;
var added = false;
$("#list > option").each(function() {
if ($(this).text() > $(selectedItem).text()) {
$(selectedItem).insertBefore($(this));
added = true;
return false;
}
});
if(!added) $(selectedItem).appendTo($("#list"));
updateHiddenField();
});
function updateHiddenField () {
$('input[name="selected_values"]').val(
$.map($('#selected_values option:selected').toArray(), function (e) {
return e.value;
})
);
}
});
PHP code:
if(!empty($_POST['selected_values'])) {
$_POST['selected_values'] = explode(',', $_POST['selected_values']);
foreach($_POST['selected_values'] as $x) {
$query = "INSERT INTO $table (id1, id2) VALUES ($id1Value, $x)";
db_query($query);
My goal is to iterate through all of the values that are moved into the left column and enter them into a database using PHP. I'm able to get this functionality to work, however, I'm having the exact same issue as seen referenced here: how can I get all options in a multi-options select using PHP?. I'm accessing the values using $_POST["leftValues"] but if the user clicks on one of the options, only that one will be entered into the database. Unfortunately, the accepted solution isn't working for me.
$("form:has(#leftValues)").on('submit', function () {
$("#leftValues option").prop('selected', true);
});
Can someone please explain to me how I can get this solution to work for me or an alternative way of ensuring $_POST["leftValues"] will contain all the options instead of only the selected/highlighted? Any response is greatly appreciated.

You could add a hidden field and update that whenever the lists change.
You'd need to update your html:
<div>
<select id="leftValues" size="5" multiple></select>
<input name="leftValues" type="hidden" />
</div>
and add a function to do the updating:
function updateHiddenField () {
$('input[name="leftValues[]"]').val(
$.map($('#leftValues option:selected').toArray(), function (e) {
return e.value;
})
);
}
And call it in each of your click handlers:
$("#btnLeft").click(function () {
var selectedItem = $("#rightValues option:selected");
$("#leftValues").append(selectedItem);
updateHiddenField();
});
$("#btnRight").click(function () {
var selectedItem = $("#leftValues option:selected"), activeValues;
$("#rightValues").append(selectedItem);
updateHiddenField();
});
Finally, you can do this in your PHP to get what you originally expected:
$_POST['leftValues'] = explode(',', $_POST['leftValues']);

Finally got it to work. I edited the submit callback, as the original solution suggested.
Added an id to my form tag:
<form id="form" method="post">
When the form is submitted, select/highlight all options in the selected_values list:
$(#form).submit(function () {
$("#selected_values > option").each(function () {
$(this).attr('selected', 'selected');
});
return true;
});

Related

Disable form submit button input=text and input=checkbox with jquery

I have a form with three inputs ([type=text], multiple input[type=checkbox] and a disabled submit button).
I want the submit button to be enabled if a user has filled in all three text-inputs and has selected at least one of the checkboxes.
I found this fiddle which works great on all three text-inputs, but I'd like to add the additional condition that at least one checkbox must be selected:
$(document).ready(function() {
var $submit = $("input[type=submit]"),
$inputs = $('input[type=text], input[type=password]');
function checkEmpty() {
// filter over the empty inputs
return $inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
}
$inputs.on('blur', function() {
$submit.prop("disabled", !checkEmpty());
}).blur(); // trigger an initial blur
});
fiddle
Add class="checkbox" in the checkboxes then modify checkEmpty() to this:
function checkEmpty() {
var text= $inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
var checkbox = false;
if ($(".checkbox:checked").length > 0) {
checkbox = true;
}
if(text == true && checkbox == true){
return true;
}else{
return false;
}
}
Then add the event on click for the checkboxes which is:
$(".checkbox").on("click", function(){
$submit.prop("disabled", !checkEmpty());
});
Hey just add input[type=checkbox] only in jquery part, here is your desired output, try below code:
Index.html
<form method="POST" action="">
User Name: <input name="Username" type="text" size="14" maxlength="14" /><br />
hobbies:<input type="checkbox" name="cricket">Cricket<input type="checkbox" name="football">football<input type="checkbox" name="hockey">hockey<br>
<input type="submit" value="Login" name="Submit" id="loggy">
</form>
<script src="https://code.jquery.com/jquery-1.12.4.js" integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
var $submit = $("input[type=submit]"),
$inputs = $('input[type=text], input[type=checkbox]');
function checkEmpty() {
return $inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
}
$inputs.on('blur', function() {
$submit.prop("disabled", !checkEmpty());
}).blur();
});
</script>
Ok i have a serious problem now.
I'm using wordpress and added:
<?php wp_head(); ?>
<?php wp_footer(); ?>
To my header.php and footer.php, cause i need them so a plugin is getting loaded.
Since i added them the working solution from Stephan Sutter isn't working anymore. The submit button is still disabled if i fill in all required forms. If i remove them it works again, but i need them for the plugin.
I think it is because the plugin adds input text to the page. Is there any way i can use the code frm Stephan for a defined form ID=#addmovie-form?

Disable submit button until all hidden inputs have a value

I have a simple form with hidden inputs and I'm trying to check whether each hidden input has a value. If all hidden inputs have a value than disable or enable the submit button. The inputs are being filled once the user clicks on an image via jquery. Ive tried multiple ways and it seems like I'm missing something....
<form method="post" action="test.php">
<div class="selections" id="accordion">
<h3>title<div class='status'>Pending</div></h3>
<div class='select-form'>
<div class='images'>
<img src='images/vote.jpg' data-value='data-value'>
<br/><span>title</span><br/>description
</div>
<input type='hidden' class='image-value' name='1' value=''>
</div>
<div class='select-form'>
<div class='images'>
<img src='images/vote.jpg' data-value='data-value2'>
<br/><span>title</span><br/>description
</div>
<input type='hidden' class='image-value2' name='2' value=''>
</div>
</div>
<input id="submit_button" type="submit" class="submit" value="SUBMIT">
</form>
the javascript goes as follows:
$( document ).ready(function() {
var $submit = $("input[type=submit]"),
$inputs = $('input[type=hidden]');
function checkEmpty() {
// filter over the empty inputs
return $inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
}
$inputs.on('blur', function() {
$submit.prop("disabled", !checkEmpty());
}).blur(); // trigger an initial blur
});
any ideas?
You could just call the checkEmpty() on img.click(), and from that function handle the disabled state.
Try it out here: JSFiddle (click the images)
$( document ).ready(function() {
var $submit = $("input[type=submit]"),
$inputs = $('input[type=hidden]');
function checkEmpty() {
var res = true;
$inputs.each( function(i,v){
if(v.value == ""){
res = false;
return false;
}
});
$submit.prop("disabled", !res);
}
$("img").click( function(){
$(this).parent().parent().find("input[type=hidden]").val("sdf");
checkEmpty();
});
checkEmpty(); //set disabled onload
});
Your trim function isn't behaving as you accept, remove it like here :
function checkEmpty() {
// filter over the empty inputs
return inputs.filter(function() {
return !(this.value);
}).length === 0;
}
Put this inside of the blur function to find out if all hidden inputs have a non empty value.
var empty=false;
$('input[type=hidden]').each(function(){
if($(this).val()==""){
empty=true;
}
});
if(empty){
//DISABLE SUBMIT
}
You're using $ in your JavaScript variables when you shouldn't be. Working fiddle: http://jsfiddle.net/keliix06/2f3cv2pk/
$( document ).ready(function() {
var submit = $("input[type=submit]"),
inputs = $('input[type=hidden]');
function checkEmpty() {
// filter over the empty inputs
return inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
}
inputs.on('blur', function() {
submit.prop("disabled", !checkEmpty());
}).blur(); // trigger an initial blur
});

Get checked item on select form - Javascript

Im learning javascript and I have this function:
function getRadioCity() {
for (index=0; index < document.form_data2.ciudades.length; index++) {
if (document.form_data2.ciudades[index].checked) {
var radioValue =form_data2.ciudades[index].value;
return parseInt(radioValue);
}
}
}
The function works fine but what if i have a select form instead radio?
For example:
<div id="content" style="display:none;">
<form name="form_data2" id="form_data2"> <br>
<select name="ciudades" id="ciudades">
<option value="33">Armenia</option>
<option value="34">Cartagena</option>
</select>
<input value="Enviar" id="btn_enviar" href="javascript:toggle() </input> <br /> <br /> <label id=" mensaje2="" type="button"> </form>
<div id="resultado2"></div>
</div>
Thanks in advance for your help. Ill tried the same thing but doenst work..
edit:
I tried to make something like this:
$(document).ready(function(){
$('#btn_enviar').click(function(){
if( validaSelect( 'ciudades','ciudades' ) == false) return false;
$.ajax({
type:'POST',
url :'upload2.php',
data: $('#form_data2').serialize(),
beforeSend : function(){
$('#mensaje2').html('Enviando datos...');
},
success: function (data){
$('#mensaje2').html('Datos enviados correctamente.');
$('#resultado2').html(data);
},
complete: function(){
$('#form_data2').slideUp();
$('#resultado2').slideDown();
$('#content2').show();
$('#flecha2').show();
var num2 = getRadioCity();
if (num2==1){
$('#armenia').show();
}
if (num2==2){
$('#cartagena').show();
alert("cartagena");
}
}
});
});
});
basically get the value depending on the select and display a div or other
You can access the value of select using selectedIndex.
document.getElementById("ciudades").onchange = function() {
alert(this.selectedIndex);
}
Each option has its own number identifying itself. In the case of a select element, the first option has a selectedIndex of 0 and the second has a selectedIndex of 1 and so on. From this you can tell which option is selected.
See DEMO.
Try this:
var num2 = document.getElementById("ciudades").selectedIndex;
if (num2==0){
$('#armenia').show();
}
if (num2==1){
$('#cartagena').show();
alert("cartagena");
}

"search" field to filter content

I'm trying to create a simple "search field", what it does is it searches if typed in text is equal to any data-attr of the boxes in the content and if so, hide everything but what found, something similar (this ain't working):
css:
.filter-div {
display: none;
}
html:
<label for="search">Search Input:</label>
<input type="search" name="filter" id="search" value="" />
<div class="filter-div" data-filter="one">one</div>
<div class="filter-div" data-filter="two">two</div>
<div class="filter-div" data-filter="three">three</div>
<div class="filter-div" data-filter="four">four</div>
<div class="filter-div" data-filter="five">five</div>
jquery:
// save the default value on page load
var filter = $('.input').val();
// on submit, compare
if ( $('.input').val() = $("data-filter") {
$(this).show();
} ​
I am also not sure if the content should be filtered with a button click or found content should pop up as click-able text in the search, or should all happen auto? Finally probably I will have to check it against more than one data-attr.
Anyone?
$('#search').on('keyup', function() {
var val = $.trim(this.value);
if (val) {
$('div[data-filter=' + val + ']').show();
} else $('div[data-filter]').hide();
});
Working sample
According to demo fiddle example in comment
var divs = $('div[data-filter]');
$('#search').on('keyup', function() {
var val = $.trim(this.value);
divs.hide();
divs.filter(function() {
return $(this).data('filter').search(val) >= 0
}).show();
});
divs.on('click', function() {
divs.not(this).hide();
var text = $.trim($(this).text());
$('#search').val(text);
});
Working sample
JavaScript:
var filter_div = $('[data-filter]');
$('#search').keyup(function(){
var val = $.trim(this.value);
filter_div.hide();
if(val.length == 0) return;
filter_div.filter(function(){
return $(this).data('filter').indexOf(val)>-1
}).show();
});
Fiddle: http://jsfiddle.net/iambriansreed/xMwS5/
​

Get values from submitted form

I have a very simple form:
<form id="toBeTranslatedForm" action="actionpage.php" method="POST" >
<textarea name="userInput" id="toBeTranslatedTextArea"></textarea>
<select id="translationOptions">//dynamically filled</select>
<input type="submit" value="Translate" />
</form>
Using Jquery I am detecting whether the form has been submitted:
function outputTranslated()
{
$('#toBeTranslatedForm').submit(function() {
//do stuff
});
}
How do I get the text typed in the text area and the option selected in the select box from the form above? Ideally I would like to put them into an array.
Javascript only, using FormData:
form.addEventListener("submit", function(e) {
e.preventDefault();
const data = new FormData(form);
for (const [name,value] of data) {
console.log(name, ":", value)
}
})
<form id="form">
<select name="sselectt">
<option value="default" defaultSelected="true">-- Select --</option>
<option value="foo">foo</option>
<option value="bar">bar</option>
</select>
<label for="inpt">remember</label>
<input id="inpt" name="rrememberr" type="checkbox" />
<button type="submit">submit</button>
</form>
You can get the data form the submit event
function outputTranslated() {
$('#toBeTranslatedForm').submit(function(evt) {
const form = evt.target;
// get the field that you want
const userInputField = form.elements['userInput'];
alert(userInputField.value);
});
}
var theArray = $('#toBeTranslatedForm').serializeArray();
See the .serializeArray docs.
On a pedantic note, that's not "from a submitted form", since you're asking for them before anything is actually submitted.
Here is how you can get value:
function outputTranslated() {
$('#toBeTranslatedForm').submit(function() {
var textareaval = $('#userInput').val();
alert(textareaval);
});
}
You can do the same for selection box by adding this line after the textareaval variable definition in the code above:
var selectval = $('#translationOptions').val();
Then, you can either use serialise, or you can put it into an array manually:
var a = [textareaval,selectval];
I think you'r looking for something like this.
$('#toBeTranslatedForm').submit(function() {
alert($(this).serialize());
return false;
});
Hope it helps
after submission, you can use just get the value by doing the following:
function outputTranslated()
{
$('#toBeTranslatedForm').submit(function() {
var textarea = $('#toBeTranslatedTextArea').val();
var allVals = [];
$('#translationOptions :checked').each(function() {
allVals.push($(this).val());
});
});}

Categories