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");
}
Related
I'm trying to access the id of an element, and slice off the num to piece together a url for an ajax call. I'm mainly using JQuery.
I have experimented with .attr() and .data() and found that they only return the first match, so everytime it would 1, no matter if I clicked on 1, 4, or 54.
.get() only returns the HTML header object, and I haven't yet found a way to access that and possibly pull out an id num.
The code:
$('.display').click(function(event) {
event.preventDefault();
//get category from h4's parent div
let $parent = $('h4').parent();
let $cat = $parent.attr('class');
let cat = String($cat);
//get id to search for...currently only returning id_1, not unique id
let $id = $('h4').get(); //need correct method here
console.log($id);
//slice off num to use in ajax url req
if($id.length == 4) {
id_num = $id.slice(-1) + '/';
} else if ($id.length == 5) {
id_num = $id.slice(-2) + '/';
} else {
id_num = $id.slice(-3) + '/';
}
console.log(id_num);
$.ajax({
type: 'GET',
url: 'https://swapi.co/api/' + $cat + id_num,
success: function(result) {
console.log(result);
}
})
<div class="container">
<h3 id="title">I made the Kessel Run in 12 parsecs.</h3>
<form id ="searchParams" method="POST">
Now, I want to know about the
<input list="cats" name="cats">
<datalist id="cats">
<option id="people" value="people"></option>
<option id="planets" value="planets"></option>
<option id="films" value="films"></option>
<option id="species" value="species"></option>
<option id="vehicles" value="vehicles"></option>
<option id="starships" value="starships"></option>
</datalist>
in Star Wars.
<input id="getInfo" type="submit">
</form>
<div class="display"></div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/twelveparsecs.js"></script>
</body>
</html>
Thank you!
your javascript can't be right to the html snippet, it starts with failures on line 2
let $parent = $('h4').parent();
// never matches on your code, you have no h4 tag
let $cat = $parent.attr('class');
// attr is no function of undefined, null pointer exception
the way to a id can be this this;
<div id="test">
<script>
console.log($('div').attr('id'));
</script>
if a tag is given more than 1 time you will get back a array of JQuery object matching on the nodes with the $('div') selector:
<div id="1">a</div>
<div id="2">b</div>
<script>
let listOfElements = $('div');
for(var i = 0; i < listOfElements.length; i++) {
var singleElementInList = $(listOfElements[i]);
var id = singleElementInList.attr('id');
console.log(id);
}
</script>
the get command is a ajax call to read a response of a url fast
I need to set the text of a HTML label with various language translations. I know how to do it when i know the ID of the label, but i want to make a general Javascript function which does not require the id. In this order, I need some thing like this:
HTML:
<label> <script> translating_function("hello"); </script> </label>
JAVASCRIPT:
function translating_function(string) {
//finding the translation (for example translated_text)
returning translated_text
}
The return of the translating_function function should be set as the text of the label.
Does any one have any idea how to do it.
Thank you very much.
var voc = [
{
"AR":"أهلا",
"ES":"¡Hola",
"EN":"hello"
},
{
"AR":"مرحبا",
"ES":"bienvenida",
"EN":"welcome"
},
{
"AR":"و",
"ES":"y",
"EN":"and"
},
{
"AR":"في اللغة العربية",
"ES":"a España",
"EN":"to English"
}
];
function translate(ele,lng){
for(var i=0;i<voc.length;i++){
for(var k in voc[i]){
if(voc[i][k] == ele.innerText.trim()){
ele.innerText = voc[i][lng];
break;
}
}
}
}
function translateTo(lng){
var trc = document.getElementsByClassName("translatable");
for(var i=0;i<trc.length;i++){
translate(trc[i],lng);
}
}
//add this function to any event button.click,select.change or on load
//translateTo("AR");
<p>
<span class='translatable'>hello</span>
<span class='translatable'>and</span>
<span class='translatable'>welcome</span>
<span class='translatable'>to English</span> :)
</p>
<select onchange='translateTo(this.value)'>
<option value='EN'>English</option>
<option value='AR'>Arabic</option>
<option value='ES'>Espain</option>
</select>
jsfriddle
<script>
function translating_function(str) {
return 'translating: ' + str;
}
</script>
<label> <script> document.write(translating_function("hello")); </script> </label>
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;
});
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());
});
});}
I have a checkbox in a form and I'd like it to work according to following scenario:
if someone checks it, the value of a textfield (totalCost) should be set to 10.
then, if I go back and uncheck it, a function calculate() sets the value of totalCost according to other parameters in the form.
So basically, I need the part where, when I check the checkbox I do one thing and when I uncheck it, I do another.
Pure javascript:
const checkbox = document.getElementById('myCheckbox')
checkbox.addEventListener('change', (event) => {
if (event.currentTarget.checked) {
alert('checked');
} else {
alert('not checked');
}
})
My Checkbox: <input id="myCheckbox" type="checkbox" />
function calc()
{
if (document.getElementById('xxx').checked)
{
document.getElementById('totalCost').value = 10;
} else {
calculate();
}
}
HTML
<input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>
If you are using jQuery.. then I can suggest the following:
NOTE: I made some assumption here
$('#my_checkbox').click(function(){
if($(this).is(':checked')){
$('input[name="totalCost"]').val(10);
} else {
calculate();
}
});
Use an onclick event, because every click on a checkbox actually changes it.
The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId.
const checkbox = $("#checkboxId");
checkbox.change(function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
});
HTML:
<input type="checkbox" onchange="handleChange(event)">
JS:
function handleChange(e) {
const {checked} = e.target;
}
Reference the checkbox by it's id and not with the #
Assign the function to the onclick attribute rather than using the change attribute
var checkbox = $("save_" + fieldName);
checkbox.onclick = function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
};
Javascript
// on toggle method
// to check status of checkbox
function onToggle() {
// check if checkbox is checked
if (document.querySelector('#my-checkbox').checked) {
// if checked
console.log('checked');
} else {
// if unchecked
console.log('unchecked');
}
}
HTML
<input id="my-checkbox" type="checkbox" onclick="onToggle()">
try
totalCost.value = checkbox.checked ? 10 : calculate();
function change(checkbox) {
totalCost.value = checkbox.checked ? 10 : calculate();
}
function calculate() {
return other.value*2;
}
input { display: block}
Checkbox: <input type="checkbox" onclick="change(this)"/>
Total cost: <input id="totalCost" type="number" value=5 />
Other: <input id="other" type="number" value=7 />
I know this seems like noob answer but I'm putting it here so that it can help others in the future.
Suppose you are building a table with a foreach loop. And at the same time adding checkboxes at the end.
<!-- Begin Loop-->
<tr>
<td><?=$criteria?></td>
<td><?=$indicator?></td>
<td><?=$target?></td>
<td>
<div class="form-check">
<input type="checkbox" class="form-check-input" name="active" value="<?=$id?>" <?=$status?'checked':''?>>
<!-- mark as 'checked' if checkbox was selected on a previous save -->
</div>
</td>
</tr>
<!-- End of Loop -->
You place a button below the table with a hidden input:
<form method="post" action="/goalobj-review" id="goalobj">
<!-- we retrieve saved checkboxes & concatenate them into a string separated by commas.i.e. $saved_data = "1,2,3"; -->
<input type="hidden" name="result" id="selected" value="<?= $saved_data ?>>
<button type="submit" class="btn btn-info" form="goalobj">Submit Changes</button>
</form>
You can write your script like so:
<script type="text/javascript">
var checkboxes = document.getElementsByClassName('form-check-input');
var i;
var tid = setInterval(function () {
if (document.readyState !== "complete") {
return;
}
clearInterval(tid);
for(i=0;i<checkboxes.length;i++){
checkboxes[i].addEventListener('click',checkBoxValue);
}
},100);
function checkBoxValue(event) {
var selected = document.querySelector("input[id=selected]");
var result = 0;
if(this.checked) {
if(selected.value.length > 0) {
result = selected.value + "," + this.value;
document.querySelector("input[id=selected]").value = result;
} else {
result = this.value;
document.querySelector("input[id=selected]").value = result;
}
}
if(! this.checked) {
// trigger if unchecked. if checkbox is marked as 'checked' from a previous saved is deselected, this will also remove its corresponding value from our hidden input.
var compact = selected.value.split(","); // split string into array
var index = compact.indexOf(this.value); // return index of our selected checkbox
compact.splice(index,1); // removes 1 item at specified index
var newValue = compact.join(",") // returns a new string
document.querySelector("input[id=selected]").value = newValue;
}
}
</script>
The ids of your checkboxes will be submitted as a string "1,2" within the result variable. You can then break it up at the controller level however you want.