So when I click the checkbox, the background colour changes. I want this function to work for all checkboxes, but it is currently only working for the first one.
function obtained() {
var obt = document.getElementsByClassName("obtained")[0];
var col = document.getElementsByClassName("entry")[0];
if (obt.checked == true) {
col.style.backgroundColor = "#2ab320";
} else {
col.style.backgroundColor = "#d3d5db";
}
}
<div class="entry">
<img class="class-name" src="image1.png">
<b>title1</b><br>content1
<input
type="checkbox"
class="obtained"
onclick="obtained()"
name="obtained"
>
</div><hr>
<div class="entry">
<img class="class-name" src="image2.png">
<b>title2</b><br>content2
<input
type="checkbox"
class="obtained"
onclick="obtained()"
name="obtained"
/>
</div><hr>
<div class="entry">
<img class="class-name" src="image3.png">
<b>title3</b><br>content3
<input
type="checkbox"
class="obtained"
onclick="obtained()"
name="obtained"
/>
</div><hr>
You could pass an instance of the checkbox to the function like so:
function obtained(element) {
var col = element.parentElement;
if (element.checked == true) {
col.style.backgroundColor = "#2ab320";
} else {
col.style.backgroundColor = "#d3d5db";
}
}
<div class="entry">
<img class="class-name" src="image1.png">
<b>title1</b><br>content1
<input
type="checkbox"
class="obtained"
onclick="obtained(this)"
name="obtained"
>
</div><hr>
<div class="entry">
<img class="class-name" src="image2.png">
<b>title2</b><br>content2
<input
type="checkbox"
class="obtained"
onclick="obtained(this)"
name="obtained"
/>
</div><hr>
<div class="entry">
<img class="class-name" src="image3.png">
<b>title3</b><br>content3
<input
type="checkbox"
class="obtained"
onclick="obtained(this)"
name="obtained"
/>
</div><hr>
In cases like this one you should declare a helper function:
function makeTogglable(element) {
const obt = element.querySelector(".obtained");
obt.addEventListener("click", () => {
if(obt.checked == true) {
element.style.backgroundColor = "#2ab320";
} else {
element.style.backgroundColor = "#d3d5db";
}
});
}
Then you can apply it your HTML elements, for example:
document.querySelectorAll('.entry').forEach(e => makeTogglable(e));
Edit: forgot about listeners
Related
I have an html table, which is structured like this:
<body>
<div class="block div-table" id="sidebar-record-block">
<div class="div-table-row">
<div class="div-table-header">Sel</div>
<div class="div-table-header">Color</div>
<div class="div-table-header">Hex</div>
</div>
<div id="field-0000" class="div-table-row">
<input type="checkbox" class="div-table-td" name="checkBox" id="cbfield-0000">
<div class="div-table-td">yellow</div>
<div class="div-table-td"></div>
</div>
<div id="field-0001" class="div-table-row">
<input type="checkbox" class="div-table-td" name="checkBox" id="cbfield-0001">
<div class="div-table-td">red</div>
<div class="div-table-td"></div>
</div>
</body>
I can iterate over the checkboxes using the code below and push the checked rows into an array:
saveButton.onclick = function(){
var checkedRowIndexes = [];
var selectedColors = [];
var checkedRows = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < checkedRows.length; i++){
if (checkedRows[i].checked){
checkedRowIndexes.push(i);
}
}
console.log(checkedRowIndexes);
}
But how would I go about iterating over the table and push the color (2ยบ col) instead, using javascript?
Thank you!
var checkedRowIndexes = [];
var selectedColors = [];
var checkedRows = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < checkedRows.length; i++) {
if (checkedRows[i].checked) {
checkedRowIndexes.push(i);
selectedColors.push(checkedRows[i].nextElementSibling.innerText);
}
}
console.log(checkedRowIndexes, selectedColors);
<div class="block div-table" id="sidebar-record-block">
<div class="div-table-row">
<div class="div-table-header">Sel</div>
<div class="div-table-header">Color</div>
<div class="div-table-header">Hex</div>
</div>
<div id="field-0000" class="div-table-row">
<input type="checkbox" class="div-table-td" name="checkBox" id="cbfield-0000">
<div class="div-table-td">yellow</div>
<div class="div-table-td"></div>
</div>
<div id="field-0001" class="div-table-row">
<input type="checkbox" class="div-table-td" name="checkBox" id="cbfield-0001">
<div class="div-table-td">red</div>
<div class="div-table-td"></div>
</div>
I saw lots of similar question where you can extract the values of Checkboxes based on the check uncheck and add them to URL, but if we have different categories of checkbox group, separate them with &.
Example:
$(document).ready(function() {
var swapRelation = "";
$("input[type=checkbox]").click(function(e) {
var seasoning = "",
parentRelation = "",
tempArray = [];
$("input:checked").each(function() {
tempArray.push($(this).attr("name").replace(/\s/g, ''));
parentRelation = $(this).closest(".wrapper").find('.catName').text().trim();
parentRelation = parentRelation.replace(/\s/g, '');
});
if (tempArray.length !== 0) {
seasoning += `${parentRelation}=` + tempArray.toString();
// if (swapRelation == parentRelation) {
// // seasoning+=`&${parentRelation}=`+tempArray.toString();
// seasoning += `${parentRelation}=` + tempArray.toString();
// }else {
// }
//tempArray = [];
swapRelation = parentRelation;
}
console.log("example.com?" + seasoning);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="catName">Fruits</div>
<div class="checkBoxWrap">
<input class="input__field" type="checkbox" name="apple" id="input-5">
<input class="input__field" type="checkbox" name="banana" id="input-6">
<input class="input__field" type="checkbox" name="mango" id="input-7">
</div>
</div>
<div class="wrapper">
<div class="catName">Vaegs</div>
<div class="checkBoxWrap">
<input class="input__field" type="checkbox" name="Okra" id="input-8">
<input class="input__field" type="checkbox" name="Patato" id="input-9">
<input class="input__field" type="checkbox" name="Tamato" id="input-10">
</div>
</div>
<div class="wrapper">
<div class="catName">Rivers</div>
<div class="checkBoxWrap">
<input class="input__field" type="checkbox" name="Ganga" id="input-11">
<input class="input__field" type="checkbox" name="yamuna" id="input-12">
<input class="input__field" type="checkbox" name="thames" id="input-13">
</div>
</div>
Expected Result on multiple Selections:
URL?Fruits=banana,mango&Vegs=okra,patato&Rivers=ganga,whateverSelected
You can use URLSearchParams to build your query string.
var usp = new URLSearchParams();
document.querySelectorAll('.wrapper').forEach((wrapperDiv)=> {
var category = wrapperDiv.querySelector('.catName').textContent;
var checkedBoxes = wrapperDiv.querySelectorAll('input[type="checkbox"]:checked');
var values = Array.from(checkedBoxes, cb=>cb.name).join('');
usp.append(category,values);
});
I hide input type and show only image which is used to choose file and on change of input I call a function :
function showpreview(file) {
var previewImg = $(file).parent().find('img').eq(0);
if (file.files && file.files[0]) {
console.log(window.URL.createObjectURL(file.files[0]));
previewImg.src = window.URL.createObjectURL(file.files[0]);
} else {
previewImg.src = "blankpreview.png";
}
console.log(previewImg.src);
console.log(previewImg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col">
<label for="exampleFormControlFile2">
<img style="height:170px;" class="img-thumbnail" src="blankpreview.png" />
</label>
<input type="file" onchange="showpreview(this)" name="Screen_2" accept="image/jpeg, image/png" class="form-control-file d-none" id="exampleFormControlFile2" required />
</div>
This show correct source and element in console but image doesn't change
You can use .attr('src',yourimage) to set src of your image tag.
Demo Code :
function showpreview(file) {
var previewImg = $(file).parent().find('img') //no need of eq..
if (file.files && file.files[0]) {
console.log(window.URL.createObjectURL(file.files[0]));
previewImg.attr('src', window.URL.createObjectURL(file.files[0])); //use .attr here
} else {
previewImg.attr('src', "blankpreview.png");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col">
<label for="exampleFormControlFile2">
<img style="height:170px;" class="img-thumbnail" src="blankpreview.png" />
</label>
<input type="file" onchange="showpreview(this)" name="Screen_2" accept="image/jpeg, image/png" class="form-control-file d-none" id="exampleFormControlFile2" required />
</div>
Because you want to work with the raw DOM element, you need to grab that in your selector...
var previewImg = $(file).parent().find('.img-thumbnail').eq(0)[0];
Note the additional [0] at the end. Let's deal with it in steps below...
$(file).parent()
.find('.img-thumbnail') // find the thumbnail image
.eq(0) // "I only want the first one you find"
[0]; // Give me the DOM element that's inside the jQuery object
function showpreview(file) {
var previewImg = $(file).parent().find('.img-thumbnail').eq(0)[0];
if (file.files && file.files[0]) {
previewImg.src = window.URL.createObjectURL(file.files[0]);
} else {
previewImg.src = "blankpreview.png";
}
console.log(previewImg.src);
console.log(previewImg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col">
<label for="exampleFormControlFile2">
<img style="height:170px;" class="img-thumbnail" src="blankpreview.png" />
</label>
<input type="file" onchange="showpreview(this)" name="Screen_2" accept="image/jpeg, image/png" class="form-control-file d-none" id="exampleFormControlFile2" required />
</div>
I'm trying to call specific div as per the input value. below is the expected result
If type "one" in input filed result should view as "Page one",
If type "two" in input filed result should be "Page two",
If type anything else in input filed result should be "Page three"
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div id="one" name="one" style="display:none;">
<h1>Page One</h1>
</div>
<div id="two" name="two" style="display:none;">
<h1>Page Two</h1>
</div>
<div id="three" name="three" style="display:none;">
<h1>Page Three</h1>
</div>
<input type="text" id="enter" name="enter" value="" />
<input type="button" value="Click here" onclick="test();">
<script>
function test() {
var v_input = document.getElementById("enter").value;
var v_one = "one";
var v_one = "two";
if (v_input = v_one) {
$('#one').show();
$('#two').hide();
$('#three').hide();
} else if (v_input = v_two) {
$('#one').hide();
$('#two').show();
$('#three').hide();
} else {
$('#one').hide();
$('#two').hide();
$('#three').show();
}
}
</script>
</body>
Please, advice how to fix this issue, thanks in advance
You can get the input from your textbox using:
const inputText = $("#enter").val();
And the you can select a given "page" to show using:
$("#" +inputText);
If the length of this selected item is 0 (which is fasley) then the page doesn't exist so you can then show the div with the id of three. If the length of the selected item is not zero (truthy) then that means the selected item exists, and so you can show it using:
$("#" +inputText).show();
You can also add a class called page to your div's so you can toggle their visibility more specifically and easily.
See working example below:
const test = function() {
const inputText = $("#enter").val();
$('.page').hide(); // hide all open pages (then later we will show the selected one)
const elemToShow = $("#" +inputText);
if(!elemToShow.length) {
$("#three").show();
} else {
$("#" +inputText).show();
}
}
.page {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="page" id="one" name="one">
<h1>Page One</h1>
</div>
<div class="page" id="two" name="two">
<h1>Page Two</h1>
</div>
<div class="page" id="three" name="three">
<h1>Page Three</h1>
</div>
<input type="text" id="enter" name="enter" value="one" />
<input type="button" value="Click here" onclick="test();">
You had various little mistakes. Re-assigning v_one variable, in if you should use == instead of = and you missed a }.I think that was all. If you already have jquery cdn defined delete mine.
<body>
<div id="one" name="one" style="display:none;">
<h1>Page One</h1>
</div>
<div id="two" name="two" style="display:none;">
<h1>Page Two</h1>
</div>
<div id="three" name="three" style="display:none;">
<h1>Page Three</h1>
</div>
<input type="text" id="enter" name="enter" value="" />
<input type="button" value="Click here" onclick="test();">
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
function test() {
var v_input = document.getElementById("enter").value;
var v_one = "one";
var v_two = "two";
if (v_input == v_one) {
$('#one').show();
$('#two').hide();
$('#three').hide();
}else if (v_input == v_two){
$('#one').hide();
$('#two').show();
$('#three').hide();
}else {
$('#one').hide();
$('#two').hide();
$('#three').show();
}
}
</script>
</body>
First, remove all inline javascript, then remove all inline styles.
Once we have that, give your elements a common class name, so that we can hide them in a single line.
After that, simply take the value and put it into the selector.
$('#btn').on('click', () => {
const value = $('#enter').val();
$('.showHide').hide();
$('#' + value).show();
});
.showHide {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="one" name="one" class="showHide">
<h1>Page One</h1>
</div>
<div id="two" name="two" class="showHide">
<h1>Page Two</h1>
</div>
<div id="three" name="three" class="showHide">
<h1>Page Three</h1>
</div>
<input type="text" id="enter" name="enter" value="" />
<input type="button" id="btn" value="Click here">
You have problem in defining the v_two and in if ==
function test() {
var v_input = document.getElementById("enter").value;
var v_one = "one";
var v_two = "two";
if (v_input == v_one) {
$('#one').show();
$('#two').hide();
$('#three').hide();
}
else if (v_input ==v_two){
$('#one').hide();
$('#two').show();
$('#three').hide();
}
else {
$('#one').hide();
$('#two').hide();
$('#three').show();
}}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<body>
<div id="one" name="one" style="display:none;">
<h1>Page One</h1>
</div>
<div id="two" name="two" style="display:none;">
<h1>Page Two</h1>
</div>
<div id="three" name="three" style="display:none;">
<h1>Page Three</h1>
</div>
<input type="text" id="enter" name="enter" value="" />
<input type="button" value="Click here" onclick="test();">
</body>
You can try this
function test() {
var v_input = document.getElementById("enter").value;
var v_one = "one";
var v_two = "two";
// all are hidden
$('#one').hide();
$('#two').hide();
$('#three').hide();
var nameId = "#three"; // variable to get id or you can keep this as empty
if (v_input == v_one) {
nameId = '#one';
} else if (v_input == v_two) {
nameId = '#two'
} else {
nameId = '#three'; // you can use this section for default behaviour
}
// Show selected name
$(nameId).show();
}
Hope this helps!
try this and let me know is it helpful or not
function test() {
var v_input = document.getElementById("enter").value;
$('#three ,#one ,#two').hide();
if (v_input == "one" || v_input == "two") {
$('#' + v_input).show();
} else {
$('#three').show();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="one" name="one" style="display:none;">
<h1>Page One</h1>
</div>
<div id="two" name="two" style="display:none;">
<h1>Page Two</h1>
</div>
<div id="three" name="three" style="display:none;">
<h1>Page Three</h1>
</div>
<input type="text" id="enter" name="enter" value="" />
<input type="button" value="Click here" onclick="test();">
What you will need, is a two way binding in pure java script to achieve your goal.
Here is the basic snippet for your code:
function DataBind(element, data) {
this.data = data;
this.element = element;
element.value = data;
element.addEventListener("change", this, false);
}
DataBind.prototype.handleEvent = function(event) {
switch (event.type) {
case "change": this.change(this.element.value);
}
};
DataBind.prototype.change = function(value) {
this.data = value;
this.element.value = value;
};
var obj = new DataBind(document.getElementById("enter"), "");
var pageField = obj.element;
pageField.onkeydown = updateNameDisplay;
pageField.onkeyup = updateNameDisplay;
pageField.onkeypress = updateNameDisplay;
function updateNameDisplay() {
//key down event
}
function test() {
var v_one = "one";
var v_two = "two";
if (obj.element.value === v_one) {
$('#one').show();
$('#two').hide();
$('#three').hide();
}
else if (obj.element.value === v_two){
$('#one').hide();
$('#two').show();
$('#three').hide();
}
else {
$('#one').hide();
$('#two').hide();
$('#three').show();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="one" name="one" style="display:none;">
<h1>Page One</h1>
</div>
<div id="two" name="two" style="display:none;">
<h1>Page Two</h1>
</div>
<div id="three" name="three" style="display:none;">
<h1>Page Three</h1>
</div>
<input type="text" id="enter" name="enter" value="" />
<input type="button" value="Click here" onclick="test();">
probably it is because you re-assign the value of var v_one
var v_one = "one";
var v_one = "two";
There are many issues in your JavaScript:
Missing the last bracket.
Missing assignment of v_two.
For comparing you have used single equal (=) it should be double equals(==).
<script type="text/javascript">
function test() {
var v_input = document.getElementById("enter").value;
var v_one = "one";
var v_two = "two";
if (v_input == v_one) {
$('#one').show();
$('#two').hide();
$('#three').hide();
}
else if (v_input == v_two){
$('#one').hide();
$('#two').show();
$('#three').hide();
}
else {
$('#one').hide();
$('#two').hide();
$('#three').show();
}
}
I have updated your javascript hope it helps.
I have a prototype.js class like this:
UserEditor = Class.create({
dataEditorDisplayed: function(editor) {
this.UserPhotoUploadEditor.clearFields();
$(idatabase.FIELD_SITE_ID).instance.disable();
$(idatabase.FIELD_CHANGE_PASSWORD).instance.enable();
this.photoName = this.photoUrl.getValue();
if (this.photoName == null || this.photoName == "") {
this.photoName = this.DEFAULT_PHOTO;
this.newPhoto = "1";
} else {
jQuery("#fileDiv").removeClass("fileupload-new").addClass("fileupload-exists");
jQuery('#fileDiv').prepend('<input type="hidden" value="" name="">');
jQuery('#fileThumb').prepend('<img id="uploaded_img" src="theImg.png"/>');
jQuery("#uploaded_img").attr("src",this.UPLOADS + this.photoName);
this.newPhoto = "0";
}
},
beforeEditorButtonClick: function(browser, toolType) {
switch (toolType) {
case browser.BUTTON_SAVE:
if (this.newPhoto == "1") {
this.UserPhotoUploadEditor.uploadFile();
return false;
}
}
return true;
},
});
jQuery('#change_clicked').on('click',function(){
UserEditor.newPhoto.val("1");
});
What I'm trying to do is , If user press the button with change_clicked id, I want to set this.newPhoto = "1" before switch statement. But everytime I try it's always 0. What's wrong, any ideas?
EDIT: HTML PART
<form id="file_upload_form" class="form-horizontal" method="post" enctype="multipart/form-data" action="ajax/user_photo_upload.ajax.php">
<h3 class="form-section map_header"><img src="_themes/1/img/map_photo_upload.png"> <?=$core->l("photo_upload");?></h3>
<div class="row-fluid">
<div class="span12">
<div class="control-group">
<label class="control-label">
<i class="icon-eye-open"></i>
<?=$core->l("upload_select_image")?>
<span class="formRequiredElement">*</span>
</label>
<div class="controls">
<div class="fileupload fileupload-new" data-provides="fileupload" data-name="myimage" id="fileDiv" >
<input type="hidden" value="1" name="myimage">
<div class="fileupload-new thumbnail" style="width: 200px; height: 150px;">
<img src="_themes/images/no_image.gif" id ="photo"/>
</div>
<div class="fileupload-preview fileupload-exists thumbnail" id ="fileThumb" style="max-width: 200px; max-height: 150px; line-height: 20px;"></div>
<div class="photoUploadAlign">
<span class="btn btn-file btn green"><span class="fileupload-new"><?=$core->l("select_image")?></span>
<span class="fileupload-exists" id="change_clicked"><?=$core->l("change_image")?></span>
<input type="file" class="default" name="file" id="file"></span>
<?=$core->l("remove_image")?>
</div>
</div>
<span class="label label-important"><?=$core->l("warning")?></span>
<span><?=$core->l("warning_note")?></span>
<iframe id="upload_target" name="upload_target" src="" style="display:none;width:0;height:0;border:0px solid #fff;"></iframe>
<input type="reset" id="clearFields" style="display:none"/>
</div>
</div>
</div>
</div>
</form>
Well, I've found the solution, and i'm writing here in case anyone else facing this problem sees,
Changing
beforeEditorButtonClick: function(browser, toolType) {
switch (toolType) {
case browser.BUTTON_SAVE:
if (UserEditor.newPhoto == "1") {
this.UserPhotoUploadEditor.uploadFile();
return false;
}
}
return true;
},
and after Prototype class :
UserEditor.newPhoto = "0";
jQuery('#change_clicked').on('click',function(){
UserEditor.newPhoto = "1";
});
jQuery('#remove_clicked').on('click',function(){
UserEditor.newPhoto = "1";
});
jQuery('#select_clicked').on('click',function(){
UserEditor.newPhoto = "1";
});
Solves the problems.